package com.tansun.easycare.rule.ruleflow.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblock;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.enums.RuleModelTypeFileEnum;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.model.SelectEditorVo;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.executionblock.dao.RuleExcutionBlockDao;
import com.tansun.easycare.rule.executionblock.entity.RuleExcutionBlock;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.ruleflow.dao.RuleFlowDao;
import com.tansun.easycare.rule.ruleflow.entity.ExtendNodeInfo;
import com.tansun.easycare.rule.ruleflow.entity.RuleFlow;
import com.tansun.easycare.rule.ruleflow.entity.RuleFlowConditions;
import com.tansun.easycare.rule.ruleflow.entity.RuleFlowRects;
import com.tansun.easycare.rule.ruleflow.model.Line;
import com.tansun.easycare.rule.ruleflow.model.Node;
import com.tansun.easycare.rule.ruleflow.model.RuleFlowCondition;
import com.tansun.easycare.rule.ruleflow.model.RuleFlowItem;
import com.tansun.easycare.rule.ruleflow.model.RuleFlowModel;
import com.tansun.easycare.rule.ruleflow.model.RuleFlowVO;
import com.tansun.easycare.rule.ruleflow.model.RuleNextTreeNode;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowConditionsService;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowRectsService;
import com.tansun.easycare.rule.ruleflow.service.RuleFlowService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.LoggerManager;
import com.tansun.rule.utils.StringUtils;


/**
 * 规则流 服务管理器实现类
 *
 * @author ZengWenfeng
 */
@Service("RuleFlowService")
public class RuleFlowServiceImpl extends RuleBaseServiceImpl<RuleFlowDao, RuleFlow> implements RuleFlowService {
    @Autowired
    private RuleFlowConditionsService ruleFlowConditionsService;
    @Autowired
    private RuleFlowRectsService ruleFlowRectsService;
    @Autowired
    private RuleVersioninfoService ruleVersioninfoService;
    @Autowired
    private RuleCodeblockService ruleCodeblockService;
    @Autowired
    private RuleManageService ruleManageService;
    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;
    @Autowired
    private RuleExcutionBlockDao ruleExcutionBlockDao;
	@Autowired
	private  RuleDataparamsService  ruleDataparamsService;
    public String minus = "-";
    public String comma = ",";
    public String semicolon = ";";

    @Override
    public List<SelectEditorVo> getAllPublishVersion(RuleVersioninfo ruleVersioninfo) throws BizException {
    	ruleVersioninfo.setIsValid("1");
//        List<RuleVersioninfo> verlist = ruleVersioninfoService.findPublishVersionList(ruleVersioninfo);
        List<RuleVersioninfo> verlist = ruleVersioninfoService.findNewPublishVersionList(ruleVersioninfo);
        List<SelectEditorVo> list = new ArrayList();
        for (RuleVersioninfo ruleVer : verlist) {
            String value = ruleVer.getModelCode();
            String name = ruleVer.getModelName() + "_" + ruleVer.getVersion();
            String version = ruleVer.getVersion().replace("v", "");
            SelectEditorVo select = new SelectEditorVo(ruleVer.getManageId(),name, value, Double.valueOf(version));
            list.add(select);
        }
        return list;
    }
    

    @Override
    public List<SelectEditorVo> getAllNewPublishVersion(RuleVersioninfo ruleVersioninfo) throws BizException {
    	ruleVersioninfo.setIsValid("1");
        List<RuleVersioninfo> verlist = ruleVersioninfoService.findNewPublishVersionList(ruleVersioninfo);

        List<SelectEditorVo> list = new ArrayList();
        for (RuleVersioninfo ruleVer : verlist) {
            String value = ruleVer.getModelCode() + "_" + ruleVer.getVersion();
            String name = ruleVer.getModelName() + "_" + ruleVer.getVersion();
            String version = ruleVer.getVersion().replace("v", "");
            SelectEditorVo select = new SelectEditorVo(ruleVer.getManageId(),name, value, Double.valueOf(version));
            list.add(select);
        }
        return list;
    }
     

    /**
     * 保存或更新规则流
     */
    public RuleManage saveOrUpdate(RuleFlowModel ruleInfo) throws Exception {
    	String projectCode = ruleInfo.getProjectCode();
        RuleManage ruleManage = new RuleManage();
        ruleManage.setId(ruleInfo.getManageId());
        ruleManage.setRankRelationId(ruleInfo.getRankRelationId());
        ruleManage.setStatus("1");
        ruleManage.setName(ruleInfo.getName());
        ruleManage.setCode(ruleInfo.getCode());
        ruleManage.setProjectCode(projectCode);
        if(StringUtils.isEmpty(ruleInfo.getModelType())) {
        	ruleManage.setModelType(RuleModelTypeEnum.RuleFlow.getCode());	
        }else {
        	ruleManage.setModelType(ruleInfo.getModelType());
        }
        ruleManage = ruleManageService.saveOrUpdate(ruleManage);
        ruleInfo.setManageId(ruleManage.getId());
        ruleInfo.setCode(ruleManage.getCode());
        ruleInfo.setVersion(ruleManage.getVersion());
        this.reBuildBpmnContent(ruleInfo);
        RuleFlow ruleFlow = new RuleFlow(ruleInfo);
        this.save(ruleFlow);
        String championChallengerInfo = null;
        List<Map<String, String>> championInfo = new ArrayList();
		String context = buildDataBpmnContent(ruleInfo, ruleManage, championInfo);

        if (context == null)
            throw new BizException("生成规则流文件异常");
        RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
        ruleVersioninfo.init(ruleManage, context);
        ruleVersioninfo.setChampionChallengerInfo(JSONObject.toJSONString(championInfo));
        
        
        this.ruleVersioninfoService.save(ruleVersioninfo);
        return ruleManage;
    }
    /**
     * 显示java代码
     * @param tableEntity
     * @throws BizException
     */
    public String showJavaCode(RuleFlowModel ruleInfo) throws BizException{
		return null;
/*        RuleManage ruleManage = ruleManageService.getById(ruleInfo.getManageId());
        ruleInfo.setManageId(ruleManage.getId());
        ruleInfo.setCode(ruleManage.getCode());
        ruleInfo.setVersion(ruleManage.getVersion());
        Map<String,String> funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
        RuleFlowModelSC ruleInfoSC= ClassChangeUtils.<RuleFlowModel,RuleFlowModelSC>changeClass(ruleInfo);
        return RuleFlowCreate.createCode(ruleInfoSC,funcParamMap);*/
    }
    /**
     * 打开新增对话框，获取初始化信息
     *
     * @param model 规则流Model对象
     * @param map   ModelMap
     */
    public RuleFlowVO getRuleFlowData(RuleFlowModel model, Map<String,String> map) throws BizException {
    	RuleFlowVO  ruleFlow = new  RuleFlowVO();
    	String ruleflowInfo = model.getRuleflowInfo();
        if (StringUtils.isEmpty(model.getManageId())) {
            ruleflowInfo = "{states:{rect1:{type:'start',text:{text:'开始'}, attr:{ x:130, y:146, width:50, height:50}, props:{name:{value:'开始'},metadata:{value:''},name:{value:''}}},rect2:{type:'end',text:{text:'结束'}, attr:{ x:650, y:146, width:50, height:50}, props:{name:{value:'结束'},metadata:{value:''},name:{value:''},terminate:{value:''}}}},paths:{},props:{props:{layout:{value:''},exception:{value:''},name:{value:''},name:{value:''},pack:{value:''},lane:{value:'swimName01;swimName02'},itemDefinition:{value:''},version:{value:''}}}}";
        } else {
        	RuleFlow condition = new RuleFlow();
            if(StringUtils.isEmpty(model.getVersion())){
            	RuleManage ruleManage = ruleManageService.findByCode(model.getCode(), model.getProjectCode());
            	model.setVersion(ruleManage.getVersion());
            }
            condition.setManageId(model.getManageId());
            condition.setVersion(model.getVersion());
//            RuleFlow condition = new RuleFlow();
//            condition.setManageId(model.getManageId());
//            condition.setVersion(model.getVersion());
            List<RuleFlow> list = this.findList(condition);
            if (list.size() == 0) {
                throw new BizException("E-101111");//未找到规则流信息
            }
            ruleflowInfo = list.get(0).getRuleflowInfo();
//			ruleflowInfo = list.get(0).getRuleflowInfo();
        }
        List<SelectEditorVo> arrRuleFlow = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrScoreModel = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrDecisionTree = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrDecisionTable = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrEvaluationIndex = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrRuleGroup = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrPolicyRuleGroup = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrGeneralRule = new ArrayList<SelectEditorVo>();//规则
        List<SelectEditorVo> arrSingleTblIndex = new ArrayList<SelectEditorVo>();
        List<SelectEditorVo> arrExecutionBlock = new ArrayList<SelectEditorVo>();//执行块
        List<SelectEditorVo> arrCodeblock = new ArrayList<SelectEditorVo>();//代码块
        List<SelectEditorVo> arrExclusions = new ArrayList<SelectEditorVo>();//排除项
        List<SelectEditorVo> arrPolicyTree = new ArrayList<SelectEditorVo>();//策略树
        List<SelectEditorVo> arrDataComponent = new ArrayList<SelectEditorVo>();//数据源
        List<SelectEditorVo> arrDataMining = new ArrayList<SelectEditorVo>();//数据源
        List<SelectEditorVo> arrfunction = new ArrayList<SelectEditorVo>();//数据源
        List<SelectEditorVo> arrStrategyFlow = new ArrayList<SelectEditorVo>();//策略流
        try {
        	RuleManage r = new RuleManage();
        	r.setProjectCode(model.getProjectCode());
        	r.setActiveFlag("1");//过滤有效版本
        	List<RuleManage> ruleList = ruleManageService.findList(r);
//            List<RuleVersioninfo> verList = ruleVersioninfoService.findPublishRuleList(model.getProjectCode());
            for (RuleManage ruleVer : ruleList) {
//                String value = ruleVer.getModelCode() + "_" + ruleVer.getVersion();注
//                String name = ruleVer.getModelName() + "_" + ruleVer.getVersion();
//                String version = ruleVer.getVersion().replace("v", "");
            	if("1".equals(ruleVer.getIsTemp())){//加
            		continue;
            	}
                String value = ruleVer.getCode();
                String name = ruleVer.getName();//加
                
                SelectEditorVo select = new SelectEditorVo(name, value,null);
//                SelectEditorVo selectVersion = new SelectEditorVo(version, value,null);注
                if (RuleModelTypeEnum.ScoreModel.getCode().equals(ruleVer.getModelType())) {
                    if (arrScoreModel.size() == 0) {
                        arrScoreModel.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrScoreModel.add(select);
                }
                if (RuleModelTypeEnum.DecisionTable.getCode().equals(ruleVer.getModelType())) {
                    if (arrDecisionTable.size() == 0) {
                        arrDecisionTable.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrDecisionTable.add(select);
                }
                if (RuleModelTypeEnum.RuleFlow.getCode().equals(ruleVer.getModelType())) {
                    if (arrRuleFlow.size() == 0) {
                        arrRuleFlow.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrRuleFlow.add(select);
                }
                if (RuleModelTypeEnum.StrategyFlow.getCode().equals(ruleVer.getModelType())) {
                    if (arrStrategyFlow.size() == 0) {
                    	arrStrategyFlow.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrStrategyFlow.add(select);
                }
                if (RuleModelTypeEnum.DecisionTree.getCode().equals(ruleVer.getModelType())) {
                    if (arrDecisionTree.size() == 0) {
                        arrDecisionTree.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrDecisionTree.add(select);
                }
                if (RuleModelTypeEnum.EvaluationIndex.getCode().equals(ruleVer.getModelType())) {
                    if (arrEvaluationIndex.size() == 0) {
                        arrEvaluationIndex.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrEvaluationIndex.add(select);
                }
                if (RuleModelTypeEnum.RuleGroup.getCode().equals(ruleVer.getModelType())) {
                    if (arrRuleGroup.size() == 0) {
                        arrRuleGroup.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrRuleGroup.add(select);
                }
                if (RuleModelTypeEnum.PolicyRuleGroup.getCode().equals(ruleVer.getModelType())) {
                    if (arrPolicyRuleGroup.size() == 0) {
                        arrPolicyRuleGroup.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrPolicyRuleGroup.add(select);
                }
                if (RuleModelTypeEnum.GeneralRule.getCode().equals(ruleVer.getModelType())) {
                    if (arrGeneralRule.size() == 0) {
                    	arrGeneralRule.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrGeneralRule.add(select);
                }
                if (RuleModelTypeEnum.SimpleRuleGroup.getCode().equals(ruleVer.getModelType())) {
                    if (arrPolicyRuleGroup.size() == 0) {
                        arrPolicyRuleGroup.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrPolicyRuleGroup.add(select);
                }
                if (RuleModelTypeEnum.SingleTblIndex.getCode().equals(ruleVer.getModelType())) {
                    if (arrSingleTblIndex.size() == 0) {
                        arrSingleTblIndex.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrSingleTblIndex.add(select);
                }
                if (RuleModelTypeEnum.Exclusions.getCode().equals(ruleVer.getModelType())) {
                    if (arrExclusions.size() == 0) {
                        arrExclusions.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrExclusions.add(select);
                }
                if (RuleModelTypeEnum.ExecutionBlock.getCode().equals(ruleVer.getModelType())) {
                    if (arrExecutionBlock.size() == 0) {
                        arrExecutionBlock.add(new SelectEditorVo("---请选择---", ""));
                    }
                    arrExecutionBlock.add(select);
                    
                }
            }
            
            RuleManage param = new RuleManage();
            param.setProjectCode(model.getProjectCode());
            param.setModelType(RuleModelTypeEnum.DataMining.getCode());
            List<RuleManage> dmList = ruleManageService.findList(param);
            arrDataMining.add(new SelectEditorVo("---请选择---", ""));
            for(RuleManage rule:dmList){
            	String value = rule.getCode();
                String name = rule.getName();
                SelectEditorVo select = new SelectEditorVo(name, value, null);
                arrDataMining.add(select);
            }
            RuleCodeblock entity = new RuleCodeblock();
            entity.setProjectCode(model.getProjectCode());
            entity.setModelType(RuleModelTypeEnum.CodeBlock.getCode());
           //获取已生效的脚本
            List<RuleCodeblock> blockList = ruleCodeblockService.findList(entity);
            for (RuleCodeblock obj : blockList) {
                if (arrCodeblock.size() == 0) {
                    arrCodeblock.add(new SelectEditorVo("---请选择---", ""));
                }
                String value = obj.getModelCode();
                String name = obj.getModelName();
                SelectEditorVo select = new SelectEditorVo(name, value, null);
                arrCodeblock.add(select);
            }
            //获取已生效的函数变量 ljt
            RuleCodeblock funcentity = new RuleCodeblock();
            funcentity.setProjectCode(model.getProjectCode());
            List<RuleCodeblock> funcList = ruleCodeblockService.findParamFuncEffectList(funcentity);
            for (RuleCodeblock obj : funcList) {
                if (arrfunction.size() == 0) {
                	arrfunction.add(new SelectEditorVo("---请选择---", ""));
                }
                String value = obj.getFunctionName();
                String name = obj.getModelName();
                SelectEditorVo select = new SelectEditorVo(name, value, null);
                arrfunction.add(select);
            }
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e);
        }
        ruleFlow.setArrRuleFlow(JSONObject.toJSONString(arrRuleFlow));
        ruleFlow.setArrCodeblock(JSONObject.toJSONString(arrCodeblock));
        ruleFlow.setArrDataComponent(JSONObject.toJSONString(arrDataComponent));
        ruleFlow.setArrDataMining(JSONObject.toJSONString(arrDataMining));
        ruleFlow.setArrDecisionTable(JSONObject.toJSONString(arrDecisionTable));
        ruleFlow.setArrDecisionTree(JSONObject.toJSONString(arrDecisionTree));
        ruleFlow.setArrEvaluationIndex(JSONObject.toJSONString(arrEvaluationIndex));
        ruleFlow.setArrExclusions(JSONObject.toJSONString(arrExclusions));
        ruleFlow.setArrExecutionBlock(JSONObject.toJSONString(arrExecutionBlock));
        ruleFlow.setArrfunction(JSONObject.toJSONString(arrfunction));
        ruleFlow.setArrPolicyRuleGroup(JSONObject.toJSONString(arrPolicyRuleGroup));
        ruleFlow.setArrGeneralRule(JSONObject.toJSONString(arrGeneralRule));
        ruleFlow.setArrPolicyTree( JSONObject.toJSONString(arrPolicyTree));
        ruleFlow.setArrRuleGroup(JSONObject.toJSONString(arrRuleGroup));
        ruleFlow.setArrScoreModel(JSONObject.toJSONString(arrScoreModel));
        ruleFlow.setArrSingleTblIndex( JSONObject.toJSONString(arrSingleTblIndex));
        ruleFlow.setArrStrategyFlow(JSONObject.toJSONString(arrStrategyFlow));
        ruleFlow.setParamData(ruleflowInfo);
        ruleFlow.setProjectCode(model.getProjectCode());
        return  ruleFlow;
      }

    
    private void  reBuildBpmnContent( RuleFlowModel model) {
        String data = model.getRuleflowInfo();
        JSONObject jsonObj = JSONObject.parseObject(data);
        if (jsonObj == null) {
            return ;
        }
        JSONObject states = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("states");
        
        Set<String>  keys =  states.keySet();
        for (String key :keys) {
        	JSONObject  state = 	states.getJSONObject(key);
        	if  (state != null) {
         		JSONObject objProps =state.getJSONObject("props");
        		
        		JSONObject objModel = objProps == null ? null : objProps.getJSONObject("model");
        		if (objModel != null) {
        			String objVal = objModel.getString("value");
        	      	String[] strArgs =StringUtils.split(objVal, "_");
                	if (strArgs != null && strArgs.length >0) {
                		objModel.put("value", strArgs[0]);                		
                	}
        		}
        	}        	
        }   
        model.setRuleflowInfo(JSON.toJSONString(jsonObj));
    	
    }
    /**
     * 生成data.bpmn内容
     *
     * @param model 规则流对象
     * @return data.bpmn内容
     */
    public String buildDataBpmnContent(RuleFlowModel model, RuleManage ruleManage, List<Map<String, String>> championInfo) throws Exception {
    	funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());
    	if (model == null || model.getCode().equals("")) {
            return "";
        }
        String code = model.getCode();
        String data = model.getRuleflowInfo();
        if (data == null || data.equals("")) {
            return "";
        }
        // 转换JSONObject
        JSONObject jsonObj = JSONObject.parseObject(data);//转换成JSONObject
        if (jsonObj == null) {
            return "";
        }
        // ----------------------------------------------------------------------------------
        // 01 解析states节点
        // ----------------------------------------------------------------------------------
        JSONObject states = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("states");
        Collection<?> statesEntrys = states.entrySet();
        Iterator<?> iStatesEntrys = statesEntrys.iterator();
        // 保存所有节点
        ArrayList<Node> alNode = new ArrayList<Node>();
        Map<String,Node> alNodeMap = new HashMap<String,Node>();
        Object objState = new Object();
        while (iStatesEntrys.hasNext()) {
            objState = iStatesEntrys.next();
            if (objState == null) {
                continue;
            }
            String strState = objState.toString();
            String id = strState.substring(0, strState.indexOf("="));
            JSONObject state = JSONObject.parseObject(strState.substring(strState.indexOf("=") + 1));
            String type = state == null ? null : state.getString("type");
            JSONObject objAttr = state == null ? null : state.getJSONObject("attr");
            String x = objAttr == null ? null : objAttr.getString("x");
            String y = objAttr == null ? null : objAttr.getString("y");
            String width = objAttr == null ? null : objAttr.getString("width");
            String height = objAttr == null ? null : objAttr.getString("height");

            JSONObject objProps = state == null ? null : state.getJSONObject("props");
            JSONObject objProps01 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("constaints");
            JSONObject objProps02 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("name");
            JSONObject objProps03 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("model");
            String strProps01 = objProps01 == null || objProps01.isEmpty() ? null : objProps01.getString("value");
            String strProps02 = objProps02 == null || objProps02.isEmpty() ? null : objProps02.getString("value");
            String strProps03 = objProps03 == null || objProps03.isEmpty() ? null : objProps03.getString("value");

            Node n = new Node();
            n.id = id;
            n.type = type;
            n.x = x;
            n.y = y;
            n.width = width;
            n.height = height;
            n.constaints = strProps01;
            n.name = strProps02;
            n.model = strProps03;
            alNode.add(n);
            alNodeMap.put(n.id, n);
        }
        // ----------------------------------------------------------------------------------
        // 02 解析paths连线
        // ----------------------------------------------------------------------------------
        JSONObject paths = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("paths");
        Collection<?> pathsEntrys = paths.entrySet();
        Iterator<?> iPaths = pathsEntrys.iterator();
        // 保存所有节点
        ArrayList<Line> alLine = new ArrayList<Line>();
        Object objPath = new Object();
        while (iPaths.hasNext()) {
            objPath = iPaths.next();
            if (objPath == null) {
                continue;
            }
            String strPath = objPath.toString();
            String id = strPath.substring(0, strPath.indexOf("="));
            JSONObject path = JSONObject.parseObject(strPath.substring(strPath.indexOf("=") + 1));
            //"path8":{"from":"rect1commato":"rect4commadots":[],"text":{"text":"TO 分支"},"textPos":{"x":0,"y":-10},"props":{"text":{"value":""}}},
            String from = path.getString("from");
            String to = path.getString("to");
            String strDots = "";
            JSONArray dots = path.getJSONArray("dots");
            if (dots != null && dots.size() > 0) {
                for (int i = 0; i < dots.size(); i++) {
                    Object xy = dots.get(i);
                    JSONObject objXy = JSONObject.parseObject(JSONObject.toJSONString(xy));

                    String objXy_x = objXy.getString("x");
                    String objXy_y = objXy.getString("y");

                    strDots += objXy_x + comma + objXy_y + semicolon;
                }
            }

            if (strDots.length() > 0) {
                strDots = strDots.substring(0, strDots.length() - 1);
            }

            JSONObject text = path.getJSONObject("text");
            String text_text = text.getString("text");

            JSONObject textPos = path.getJSONObject("textPos");
            String x = textPos.getString("x");
            String y = textPos.getString("y");

            JSONObject props = path.getJSONObject("props");
            JSONObject props_text = props.getJSONObject("text");
            String value = props_text.getString("value");

            JSONObject props_constaints = props.getJSONObject("constaints");
            String constaints = props_constaints==null?null:props_constaints.getString("value");
            
            
            Line line = new Line();
            line.id = id;
            line.from = from;
            line.to = to;
            line.dots = strDots;
            line.text = text_text;
            line.x = x;
            line.y = y;
            line.value = value;
            line.constaints = constaints;
            alLine.add(line);
        }
        // ----------------------------------------------------------------------------------
        // 03 解析props节点
        // ----------------------------------------------------------------------------------
        JSONObject props = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("props");
        JSONObject props_props = props.getJSONObject("props");

        //
        JSONObject props_name = props_props == null ? null : props_props.getJSONObject("name");
        JSONObject props_flag = props_props == null ? null : props_props.getJSONObject("flag");
        JSONObject props_pack = props_props == null ? null : props_props.getJSONObject("pack");
        JSONObject props_lane = props_props == null ? null : props_props.getJSONObject("lane");
        JSONObject props_itemDefinition = props_props == null ? null : props_props.getJSONObject("itemDefinition");
        JSONObject props_version = props_props == null ? null : props_props.getJSONObject("version");

        String strFlag = props_name == null ? null : props_name.getString("value");
        String strName = props_flag == null ? null : props_flag.getString("value");
        String strPack = props_pack == null ? null : props_pack.getString("value");
        String strLane = props_lane == null ? null : props_lane.getString("value");
        String strItemDefinition = props_itemDefinition == null ? null : props_itemDefinition.getString("value");
        String strVersion = props_version == null ? null : props_version.getString("value");

        // ----------------------------------------------------------------------------------
        // 04 生成文件
        // ----------------------------------------------------------------------------------
        insertUpdateNode(alNode, alLine);//分支节点前插入一个空节点以执行同步动作
        String space = "    ";
        String wrap = "\n";

        StringBuffer content = new StringBuffer();
        content.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + wrap);
        content.append("<definitions id=\"Definition\"" + wrap);
        content.append(space + "targetNamespace=\"http://www.jboss.org/drools\"" + wrap);
        content.append(space + "typeLanguage=\"http://www.java.com/javaTypes\"" + wrap);
        content.append(space + "expressionLanguage=\"http://www.mvel.org/2.0\"" + wrap);
        content.append(space + "xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"" + wrap);
        content.append(space + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + wrap);
        content.append(space + "xsi:schemaLocation=\"http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd\"" + wrap);
        content.append(space + "xmlns:g=\"http://www.jboss.org/drools/flow/gpd\"" + wrap);
        content.append(space + "xmlns:bpmndi=\"http://www.omg.org/spec/BPMN/20100524/DI\"" + wrap);
        content.append(space + "xmlns:dc=\"http://www.omg.org/spec/DD/20100524/DC\"" + wrap);
        content.append(space + "xmlns:di=\"http://www.omg.org/spec/DD/20100524/DI\"" + wrap);
        content.append(space + "xmlns:tns=\"http://www.jboss.org/drools\">" + wrap);
        content.append(wrap);

        if (strItemDefinition != null) {
            if (strItemDefinition.indexOf(semicolon) >= 0) {
                String[] arrItem = strItemDefinition.split(semicolon);
                for (int i = 0; i < arrItem.length; i++) {
                    String curItem = arrItem[i];
                    if (curItem.indexOf(comma) >= 0) {
                        String[] itemDefinitionProps = curItem.split(comma);
                        content.append(space + "<itemDefinition id=\"_" + itemDefinitionProps[0] + "Item" + "\" structureRef=\"" + itemDefinitionProps[1] + "\"/>" + wrap);
                    }
                }
            } else {
                if (strItemDefinition.indexOf(comma) >= 0) {
                    String[] itemDefinitionProps = strItemDefinition.split(comma);
                    //<itemDefinition id="_theStutasItem" structureRef="Boolean" />
                    content.append(space + "<itemDefinition id=\"_" + itemDefinitionProps[0] + "Item" + "\" structureRef=\"" + itemDefinitionProps[1] + "\"/>" + wrap);
                }
            }
            content.append(wrap);
        }
        strFlag = code;
        strPack = "com.tansun.policyrulegroup";
        if (strVersion == null || strVersion.length() < 0) {
            strVersion = model.getVersion();
        }
//        content.append(space + "<process processType=\"Private\" isExecutable=\"true\" id=\"" + strFlag + "_" + model.getVersion() + "\" name=\"" + strName + "\" tns:packageName=\"" + strPack + "\" tns:version=\"" + strVersion + "\">" + wrap);
        content.append(space + "<process processType=\"Private\" isExecutable=\"true\" id=\"" + strFlag + "\" name=\"" + ruleManage.getName() + "\" tns:packageName=\"" + strPack + "\" tns:version=\"" + strVersion + "\">" + wrap);

        content.append(space + space + "<extensionElements>" + wrap);
        content.append(space + space + space + "<tns:import name=\"java.util.*\"/>" + wrap);
        content.append(space + space + space + "<tns:import name=\"com.tansun.rule.utils.*\" />" + wrap);
        content.append(space + space + space + "<tns:import name=\"com.tansun.ruledata.data.dao.DataMiningDao\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"ruleHelper\" type=\"com.tansun.rule.utils.RuleHelper\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"droolsRuleLog\" type=\"com.tansun.rule.utils.DroolsRuleLog\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"dataMap\" type=\"java.util.Map\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"metaMap\" type=\"java.util.Map\" />" + wrap);
        content.append(space + space + "</extensionElements>" + wrap);
        if (strItemDefinition != null) {
            content.append(space + space + "<!-- process variables -->" + wrap);
            if (strItemDefinition.indexOf(semicolon) >= 0) {
                String[] arrItem = strItemDefinition.split(semicolon);
                for (int i = 0; i < arrItem.length; i++) {
                    String curItem = arrItem[i];
                    if (curItem.indexOf(comma) >= 0) {
                        String[] ItemDefinitionProps = curItem.split(comma);
                        content.append(space + space + "<property id=\"" + ItemDefinitionProps[0] + "\" itemSubjectRef=\"_" + ItemDefinitionProps[0] + "Item" + "\"/>" + wrap);
                    }
                }
            } else {
                if (strItemDefinition.indexOf(comma) >= 0) {
                    String[] ItemDefinitionProps = strItemDefinition.split(comma);
                    content.append(space + space + "<property id=\"" + ItemDefinitionProps[0] + "\" itemSubjectRef=\"_" + ItemDefinitionProps[0] + "Item" + "\"/>" + wrap);
                }
            }
        }
        content.append(wrap);
        if (strLane != null && strLane.length() > 0) {
            content.append(space + space + "<laneSet>" + wrap);
            if (strLane.indexOf(semicolon) >= 0) {
                String[] arrLaneProp = strLane.split(semicolon);
                for (int i = 0; i < arrLaneProp.length; i++) {
                    content.append(space + space + space + "<lane name=\"" + arrLaneProp[i] + "\"></lane>" + wrap);
                }
            } else {
                content.append(space + space + space + "<lane name=\"" + strLane + "\"></lane>" + wrap);
            }
            content.append(space + space + "</laneSet>" + wrap);
            content.append(wrap);
            content.append(space + space + "<!-- nodes -->" + wrap);
            List<Node> nodeList = new ArrayList<Node>();
            // 遍历节点
            if (alNode != null && alNode.size() > 0) {
                for (int i = 0; i < alNode.size(); i++) {
                    Node curNode = alNode.get(i);
                    nodeList.add(curNode);
                    if (curNode.type != null) {
                        if (curNode.type.equals("start")) {
                            content.append(space + space + "<startEvent id=\"" + curNode.id + "\"/>" + wrap);
                        } else if (curNode.type.equals("end")) {
                            content.append(space + space + "<endEvent id=\"" + curNode.id + "\" name=\"" + curNode.name + "\"/>" + wrap);
                        } else if (curNode.type.equals("task")) {
                            content.append(space + space + "<businessRuleTask id=\"" + curNode.id + "\" name=\"" + curNode.name + "\">" + wrap);
                        } else if (curNode.type.equals("codeblock") || curNode.type.equals("dataComponent")) {
                            content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                            String codeSc = null;
                            if (curNode.type.equals("codeblock")) {
                                codeSc = StringEscapeUtils.escapeXml10(ruleCodeblockService.findCodeblocksByCode(curNode.model, model.getProjectCode()));
                            } else {
                                //找数据源的代码
                                String[] arr = curNode.model.split("_");
                                RuleManage dcManage = ruleManageService.findByCode(arr[0], model.getProjectCode());
                                RuleVersioninfo con = new RuleVersioninfo();
                                con.setManageId(dcManage.getId());
                                con.setVersion(arr[1]);
                                List<RuleVersioninfo> list = ruleVersioninfoService.findList(con);
                                codeSc = StringEscapeUtils.escapeXml10(list.get(0).getRuleContent());
                            }
                            if (codeSc == null)
                                codeSc = "";
                            content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        } else if (curNode.type.equals("func")) {
                            content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                            String codeSc = curNode.model+"(dataMap,metaMap);";
                            content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        } else if (curNode.type.equals("fork")) {
                            content.append(space + space + "<inclusiveGateway id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" gatewayDirection=\"Diverging\"/>" + wrap);
                        } else if (curNode.type.equals("join")) {
                            content.append(space + space + "<exclusiveGateway id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" gatewayDirection=\"Converging\"/>" + wrap);
                        } else if (curNode.type.equals("ruleFlow") || curNode.type.equals("executionBlock") ) {
                        	content.append(space + space + "<callActivity id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" calledElement=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</callActivity>" + wrap);
                        }else if (curNode.type.equals("champion")) {
                        	
                        }                        
                        else if ("policyRuleGroup".equals(curNode.type) && curNode.model!=null && curNode.model.startsWith("EXN")) {
                        	RuleManage rm = ruleManageService.findByCode(curNode.model, ruleManage.getProjectCode());
                            content.append(space + space + "<callActivity id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" calledElement=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</callActivity>" + wrap);
                        }else if(curNode.type.equals("bigdata")){
                        	String codeSc = "System.out.println(\""+curNode.name+"\");";
                        	content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                        	content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        }else if(curNode.type.equals("datamining")){
                        	String codeSc = "droolsRuleLog.addLogs(\""+curNode.model+"\", \"datamining\", \""+curNode.model+ "\", \""+curNode.model+ "\", \""+curNode.model+ "\", 1);\r\n";
                        	codeSc += "DataMiningDao.evaluatePmml(\""+curNode.model+"\",\""+model.getProjectCode()+"\",dataMap);";
                        	content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                        	content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        }else {
                            content.append(space + space + "<businessRuleTask id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" g:ruleFlowGroup=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</businessRuleTask>" + wrap);
                        }
                    }
                }
            }
            content.append(wrap);
            content.append(space + space + "<!-- connections -->" + wrap);

            // 遍历连线
            List<RuleFlowItem> forkItemList = new ArrayList<RuleFlowItem>();
            //收集引用数据
            Map<String, RuleReferenceData> refMap = new HashMap();
            //冠军，挑战者信息
            Map<String, String> champion = new HashMap<>();
            String championInfoStr = "";
            if (alLine != null && alLine.size() > 0) {
                HashMap<String, List<RuleFlowCondition>> mapCondition = new HashMap<String, List<RuleFlowCondition>>();
                Map<String,ExtendNodeInfo> outCount = new HashMap<>();
                Map<String,ExtendNodeInfo> intCount = new HashMap<>();
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);
                    if(!outCount.containsKey(curLine.from)) {
                    	ExtendNodeInfo tmp = new ExtendNodeInfo();
                    	tmp.setCount(1);
                    	tmp.getRefLineList().add(curLine);
                    	tmp.setFrom(curLine.from);
                    	outCount.put(curLine.from, tmp);
                    }else {
                    	ExtendNodeInfo tmp = outCount.get(curLine.from);
                    	tmp.setCount(tmp.getCount()+1);
                    	tmp.getRefLineList().add(curLine);
                    	tmp.setFrom(curLine.from);
                    	outCount.put(curLine.from,tmp);
                    }
                    if(!intCount.containsKey(curLine.oriTo)) {
                    	ExtendNodeInfo tmp = new ExtendNodeInfo();
                    	tmp.setCount(1);
                    	tmp.getRefLineList().add(curLine);
                    	intCount.put(curLine.oriTo, tmp);
                    }else {
                    	ExtendNodeInfo tmp = intCount.get(curLine.oriTo);
                    	tmp.setCount(tmp.getCount()+1);
                    	tmp.getRefLineList().add(curLine);
                    	intCount.put(curLine.oriTo,tmp);
                    }
                }
                for(Entry<String,ExtendNodeInfo> entry:outCount.entrySet()) {
                	if(entry.getValue().getCount()>1) {
                		Node  chaNode=  isChampion(entry.getValue().getFrom(), alNode);
                		if (chaNode != null) {
	                		content.append(space + space + "<inclusiveGateway id=\"" + chaNode.id + "\" name=\"" + chaNode.id + "\" gatewayDirection=\"Diverging\"/>" + wrap);
                		}else {
	                		Node fork = new Node();
	                		fork.id="rect"+StringUtils.generateTenUuid();
	                		fork.type="fork";
	                		fork.x="10";
	                		fork.y="10";
	                		fork.width="10";
	                		fork.height="10";
	                		alNode.add(fork);
	                		Node forkTree = alNodeMap.get(entry.getValue().getFrom());
	                		String forkName = fork.id;
	                		if(forkTree!=null) {
	                			forkName = forkTree.name;
	                		}
	                		content.append(space + space + "<inclusiveGateway id=\"" + fork.id + "\" name=\"" + forkName + "\" gatewayDirection=\"Diverging\"/>" + wrap);
	                		entry.getValue().setNode(fork);
	                		Line newLine = new Line();
	                		newLine.from = entry.getKey();
	                		newLine.to = fork.id;
	                		newLine.oriTo = fork.id;
	                		alLine.add(newLine);
	                		List<RuleFlowCondition> conditionList = new ArrayList<>();
	                		for(Line item:entry.getValue().getRefLineList()) {
	                			item.from = fork.id;
	                			RuleFlowCondition citem = new RuleFlowCondition();
	                			citem.setFromTo(item.from+"-"+item.oriTo);
	                			citem.setItemStr(item.constaints);
	                			conditionList.add(citem);
	                		}
	                		fork.setConditionList(conditionList);
                		}	
                	}
                }
                for(Entry<String,ExtendNodeInfo> entry:intCount.entrySet()) {
                	if(entry.getValue().getCount()>1) {
                		Node join = new Node();
                		join.id="rect"+StringUtils.generateTenUuid();
                		join.type="join";
                		join.x="10";
                		join.y="10";
                		join.width="10";
                		join.height="10";
                		alNode.add(join);
                		content.append(space + space + "<exclusiveGateway id=\"" + join.id + "\" name=\"" + join.name + "\" gatewayDirection=\"Converging\"/>" + wrap);
                		entry.getValue().setNode(join);
                		Line newLine = new Line();
                		newLine.from = join.id;
                		newLine.to = entry.getKey();
                		newLine.oriTo = entry.getKey();
                		alLine.add(newLine);
                		for(Line item:entry.getValue().getRefLineList()) {
                			item.to = join.id;
                		}
                	}
                }
                
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);
                    String lineId = curLine.from + minus + curLine.oriTo;
                    String name = curLine.text;
                    Node cham = isChampion(curLine.from, alNode);
                    if (cham != null) {
                        RuleFlowCondition condition = null;
                        boolean championFlag = false;
						if (cham.constaints != null && cham.constaints.length() > 0){
							List<RuleFlowCondition> conditionList = null;
							if(mapCondition.containsKey(cham.id)){
								conditionList = mapCondition.get(cham.id);
							}else{
								String conditionStr = cham.constaints.replace("#", "\"");
								conditionList = JSON.parseArray(conditionStr, RuleFlowCondition.class);
								mapCondition.put(cham.id, conditionList);
							}
							for (int j = 0; j < conditionList.size(); j++) {
								RuleFlowCondition temp = conditionList.get(j);
								String isNull = String.valueOf(temp.getIsChampion());
								if(isNull.equals("null")) {
									break;
								}
								boolean flag = temp.getIsChampion();
								if(flag) {
									championFlag = true;
								}
								if(org.apache.commons.lang3.StringUtils.isEmpty(temp.getFromTo())){
									throw new Exception(cham.name+"信息异常，请重新保存分支!");
								}

								if(temp.getFromTo().equals(lineId)){
									condition = temp;
								}
							}
						}
						String seqName = StringUtils.generateTenUuid();
						if(championFlag) {
							boolean isChampion = condition.getIsChampion();
							if(isChampion){
								champion.put("champion", "true");
								champion.put("name", name);
								championInfoStr = " ruleHelper.getValue(dataMap,\"championInfo.champion\")==\"true\"";
								championInfo.add(champion);
							}else{
								Map<String, String> challenger = new HashMap<>();
								challenger.put("challenger", String.valueOf(i));
								challenger.put("name", name);
								championInfoStr = " ruleHelper.getValue(dataMap,\"championInfo.challenger\")==\""+i+"\"";
								championInfo.add(challenger);
							}
						}
						
                        content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\" name=\"" + seqName + "\" tns:priority=\"" + "0" + "\">" + wrap);
                        content.append(space + space + space + "<conditionExpression xsi:type=\"tFormalExpression\" >" +championInfoStr + "</conditionExpression>" + wrap);
                        content.append(space + space + "</sequenceFlow>" + wrap);
                    }else {
	                    // 当前线段的开始节点是否是分支节点
	                    Node fork = isFork(curLine, alNode);
	                    // 线的起始节点是分支节点
	                    if (fork != null) {
	                        // 分支节点条件
                                RuleFlowCondition condition = null;
	                            List<String>  clsList  = new  ArrayList<>();
	    						if (fork.getConditionList() != null && fork.getConditionList().size() > 0){
	    							List<RuleFlowCondition> conditionList = null;
	    							if(mapCondition.containsKey(fork.id)){
	    								conditionList = mapCondition.get(fork.id);
	    							}else{
	    								mapCondition.put(fork.id, fork.getConditionList());
	    								conditionList = fork.getConditionList();
	    							}
	    							for (int j = 0; j < conditionList.size(); j++) {
	    								RuleFlowCondition temp = conditionList.get(j);
	
	    								String tmpItemStr =temp.getItemStr().replace("@", "\"");
	    								if (!StringUtils.isEmpty(tmpItemStr)) {
		    								List<RuleFlowItem> itemList =JSON.parseArray(tmpItemStr, RuleFlowItem.class);
		    								if (itemList !=null  ) {
		    									for  (RuleFlowItem conFlowItem:itemList) {
			    								    String  conValue =	conFlowItem.getControlValue().replace("%", "\"");
			    								    conFlowItem.setControlValue(conValue);
			    								    if (conValue !=null && !conValue.equals("otherwise")) {
			    								    	clsList.add(conValue);
			    								    }
		    									}
		    								}
	    								}
	    								if(org.apache.commons.lang3.StringUtils.isEmpty(temp.getFromTo())){
	    									throw new Exception(fork.name+"信息异常，请重新保存分支!");
	    								}
	    								if(temp.getFromTo().equals(lineId)){
	    									condition = temp;
	    								}
	    							}
	    						}
	    						String mapStr = "";//默认条件都是可以走分支
	    						String seqName = StringUtils.generateTenUuid();

	                            if (condition!=null && !StringUtils.isEmpty(condition.getItemStr())) {
	                            	seqName = condition.getName();
	                                String forkItemStr = condition.getItemStr().replace("@", "\"");
	                                List<RuleFlowItem> conList = JSON.parseArray(forkItemStr, RuleFlowItem.class);
	                                forkItemList.addAll(conList);
	                                String  enmStr=null;
	   
	                                for (RuleFlowItem forkItem : conList) {
	                                    String dataType = forkItem.getDataType();
	                                    String domain = forkItem.getDomain();
	                                    String symbol = forkItem.getSymbol();
    								    String controlValue = forkItem.getControlValue().replace("%", "\"");
    								    forkItem.setControlValue(controlValue);
	                                    enmStr =null;
	                                    if (clsList.size()==0 && "otherwise".equals(controlValue)) {
	                                    	continue;
	                                    }else if (clsList.size()>0&& "otherwise".equals(controlValue) ) {
	                                    	String strList =StringUtils.join(clsList, ",");
	                                     	enmStr = "ruleHelper.isNotContains(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+strList+"\")";
	                                    }
	                                    if (dataType.toLowerCase().equals("string") || dataType.toLowerCase().equals("emun")) {
	                                        if (StringUtils.isNotEmpty(domain)) {
	                                            // 类型字符串、domain不为空、操作符为0:   not in
	                                        	controlValue = controlValue.substring(1, controlValue.length() - 1);
	                                        	if (controlValue != null) {
	                                        		controlValue=StringUtils.replace(controlValue, "\"", "");
	                              
	                                        	}
	                                            if (symbol.equals("0")) {
	                                            	enmStr = "ruleHelper.isNotContains(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+controlValue+"\")";
	                                            }
	                                            // 类型字符串、domain不为空、操作符为1:   in
	                                            else if (symbol.equals("1")) {
	                                            	enmStr = "ruleHelper.isExistsEnum(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+controlValue+"\")";
	                                            }
	                                        } else {
	                                            if (symbol.equals("startsWith") || symbol.equals("endsWith")) {
	                                                symbol = "." + symbol;
	                                                controlValue = "(\"" + controlValue + "\")";
	                                            } else {
	                                                controlValue = "\"" + controlValue + "\"";
	                                            }
	                                        }
	                                    } else if (dataType.toLowerCase().equals("double") || dataType.toLowerCase().equals("long") || dataType.toLowerCase().equals("date")) {
	                                        // 操作符进行转译
	                                        if (symbol.equals(">")) {
	                                            symbol = "&gt;";
	                                        } else if (symbol.equals(">=")) {
	                                            symbol = "&gt;=";
	                                        } else if (symbol.equals("<")) {
	                                            symbol = "&lt;";
	                                        } else if (symbol.equals("<=")) {
	                                            symbol = "&lt;=";
	                                        }
	                                        symbol = " " + symbol + " ";
	                                        if (dataType.toLowerCase().equals("date")) {
	                                            controlValue = "\"" + controlValue + "\"";
	                                        }else {
	    							            //20171103 modify 
	    										if (controlValue.startsWith("{") && controlValue.endsWith("}")) {
	    											controlValue=StringUtils.replace(controlValue, "￥", "\"");
	    											Map<String, String> controlMap = (new ObjectMapper()).readValue(controlValue, Map.class);
	    											controlValue = genernalWhenStr(controlMap.get("className"),controlMap.get("nameEN"),"ruleflow"); 
	    											//controlValue = " ruleHelper.getValue(dataMap,\"" + controlMap.get("className") + "." + controlMap.get("nameEN") + "\")";
	    											String key = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
	    											ruleReferenceDataService.collectFromMap(controlMap, key, "in", ruleManage, refMap);
	    										}
	                                        }
	                                    } else if (dataType.toLowerCase().equals("boolean")) {
	                                        controlValue = "";
	                                        // 类型字符串、domain为空、操作符为0:   !=
	                                        if (symbol.equals("0")) {
	                                            controlValue = "false";
	                                        }
	                                        // 类型字符串、domain为空、操作符为1:   ==
	                                        else if (symbol.equals("1")) {
	                                            controlValue = "true";
	                                        }
	                                        symbol = " == ";
	                                    }
	                                    String leftOpt = forkItem.getLeftOpt();
	                                    if (!StringUtils.isEmpty(leftOpt)) {
	                                        leftOpt = leftOpt.toUpperCase();
	                                        leftOpt = leftOpt.replace("AND", "&amp;&amp;").replace("OR", "||");
	                                    }
	                                    String rightOpt = forkItem.getRightOpt();
	                                    if (!StringUtils.isEmpty(rightOpt)) {
	                                        rightOpt = rightOpt.toUpperCase();
	                                        rightOpt = rightOpt.replace("AND", "&amp;&amp;").replace("OR", "||");
	                                    }
	                                    leftOpt = leftOpt == null ? "" : leftOpt;
	                                    rightOpt = rightOpt == null ? "" : rightOpt;
	                                    if (enmStr != null) {
	                                    	mapStr +=leftOpt+enmStr +rightOpt;
	                                    }else {
	                                      String tmpStr = genernalWhenStr(forkItem.getClassName(),forkItem.getNameEN(),"ruleflow"); 
	                                      mapStr += leftOpt + tmpStr + symbol +" " + controlValue + rightOpt;
	                                    }
	                                }
	                            }
	                            if(StringUtils.isEmpty(mapStr)) {
	                            	mapStr = "ruleHelper.trueFlag==true";
	                            }
	                            String paraPriority = "0";
	                            content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\" name=\"" + seqName + "\" tns:priority=\"" + paraPriority + "\">" + wrap);
	                            content.append(space + space + space + "<conditionExpression xsi:type=\"tFormalExpression\" >" + mapStr+championInfoStr + "</conditionExpression>" + wrap);
	                            content.append(space + space + "</sequenceFlow>" + wrap);
	//                        } else {
	//                            content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\"/>" + wrap);
	//                        }
	                         
	                    } else {
	                        content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\"/>" + wrap);
	                    }
                    } 
                }
            }
            content.append(space + "</process>" + wrap);
            content.append(wrap);
            content.append(space + "<bpmndi:BPMNDiagram>" + wrap);
            content.append(space + space + "<bpmndi:BPMNPlane bpmnElement=\"" + strFlag + "\">" + wrap);
            // 遍历节点
            if (alNode != null && alNode.size() > 0) {
                for (int i = 0; i < alNode.size(); i++) {
                    Node curNode = alNode.get(i);
                    if (curNode.type.equals("ruleFlow") || curNode.type.equals("dataInit") || curNode.type.equals("decisionTree") || curNode.type.equals("decisionTable") || curNode.type.equals("evaluationIndex") || curNode.type.equals("scoreModel") || curNode.type.equals("ruleGroup") || curNode.type.equals("policyRuleGroup")) {
                        curNode.width = "110";
                        curNode.height = "48";
                    }
                    content.append(space + space + space + "<bpmndi:BPMNShape bpmnElement=\"" + curNode.id + "\">" + wrap);
                    content.append(space + space + space + space + "<dc:Bounds x=\"" + curNode.x + "\" y=\"" + curNode.y + "\" width=\"" + curNode.width + "\" height=\"" + curNode.height + "\"/>" + wrap);
                    content.append(space + space + space + "</bpmndi:BPMNShape>" + wrap);
                }
            }
            content.append(wrap);
            // 遍历节点
            if (alLine != null && alLine.size() > 0) {
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);

                    String lineId = curLine.from + minus + curLine.to;
                    content.append(space + space + space + "<bpmndi:BPMNEdge bpmnElement=\"" + lineId + "\">" + wrap);
                    Node nodeFrom = getNodeById(curLine.from, alNode);
                    String x = nodeFrom.x;
                    String y = nodeFrom.y;
                    String w = nodeFrom.width;
                    String h = nodeFrom.height;
                    x = calcValue(x, w);
                    y = calcValue(y, h);
                    content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);

                    //
                    String dots = curLine.dots;
                    if (dots != null && dots.trim().length() > 0) {
                        if (dots.indexOf(semicolon) >= 0) {
                            String[] arrDot = dots.split(semicolon);
                            for (int k = 0; k < arrDot.length; k++) {
                                String dot = arrDot[k];
                                String[] arr = dot.split(comma);
                                x = arr[0];
                                y = arr[1];

                                content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                            }
                        } else {
                            String[] arr = dots.split(comma);
                            x = arr[0];
                            y = arr[1];

                            content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                        }
                    }
                    Node nodeTo = getNodeById(curLine.to, alNode);
                    x = nodeTo.x;
                    y = nodeTo.y;
                    w = nodeTo.width;
                    h = nodeTo.height;

                    x = calcValue(x, w);
                    y = calcValue(y, h);

                    content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                    content.append(space + space + space + "</bpmndi:BPMNEdge>" + wrap);
                }
            }
            content.append(space + space + "</bpmndi:BPMNPlane>" + wrap);
            content.append(space + "</bpmndi:BPMNDiagram>" + wrap);
            content.append("</definitions>" + wrap);
            String key = "";
            List<RuleFlowRects> rectList = new ArrayList<RuleFlowRects>();
            for (Node node : nodeList) {
                RuleFlowRects rect = new RuleFlowRects(node);
                rectList.add(rect);
                if (rect.getRectType() !=null && rect.getRectType().equals("func") ) {
                	RuleReferenceData ruleReferenceData  = new  RuleReferenceData();
                	ruleReferenceData.setClassName(rect.getRectCode());
                	ruleReferenceData.setNameen(rect.getRectVersion());;
                	ruleReferenceData.setNamecn(rect.getRectName());
                	ruleReferenceData.setDataType("func");
                    key = ruleReferenceData.getClassName() + "|" + ruleReferenceData.getNameen() + "|out";
                    ruleReferenceDataService.collectCommonData(ruleReferenceData, key, "out", ruleManage, refMap);
                	
                }
            }
            List<RuleFlowConditions> rectConList = new ArrayList<RuleFlowConditions>();

            for (RuleFlowItem forkItem : forkItemList) {
                RuleFlowConditions condition = new RuleFlowConditions(forkItem);
                key = condition.getClassName() + "|" + condition.getNameen() + "|in";
                ruleReferenceDataService.collectCommonData(condition, key, "in", ruleManage, refMap);
                rectConList.add(condition);
            }
            for (Map<String, String> ccmap : championInfo) {
                RuleFlowConditions condition = new RuleFlowConditions();
                condition.setNameen(ccmap.get(key));
                if(ccmap.containsKey("champion")) {
                	condition.setClassName("championInfo");
                	condition.setNameCn(ccmap.get("name"));
                	condition.setNameen("champion");
                }else if(ccmap.containsKey("challenger")) {
                	condition.setClassName("championInfo");
                	condition.setNameCn(ccmap.get("name"));
                	condition.setNameen("challenger");
                }
                key = condition.getClassName() + "|" + condition.getNameen() + "|in";
                ruleReferenceDataService.collectCommonData(condition, key, "in", ruleManage, refMap);
			}
            
            
            //保存数据数据
            this.ruleReferenceDataService.saveReferenceData(refMap);
            ruleFlowRectsService.insertBatch(rectList, new String[]{"id", "manageId", "projectCode", "version"},
                    new Object[]{null, model.getManageId(), model.getProjectCode(), model.getVersion()}, true);
            if (rectConList.size() > 0)
                ruleFlowConditionsService.insertBatch(rectConList, new String[]{"id", "manageId", "projectCode", "version"},
                        new Object[]{null, model.getManageId(), model.getProjectCode(), model.getVersion()}, true);
        }
        System.out.println(content.toString());
        return content.toString();
    }
    

    
    
    
    
     /**
     * 在分支节点前插入一个空规则集节点
     *
     * @param alNode 节点对象
     * @param alLine 线段对象
     */
    private void insertUpdateNode(List<Node> alNode, List<Line> alLine) throws Exception {
        //RuleVersioninfo emptyRule = ruleVersioninfoService.getEmptyRuelSet();
        List<Node> newNodeList = new ArrayList<Node>();
        for (Line ln : alLine) {
            ln.oriTo = ln.to;
        }
//        for (Node cur : alNode) {
//            if (!cur.type.equals("fork")) {
//                continue;
//            }
//            Node newNode = new Node();
//            newNode.width = cur.width;
//            newNode.height = cur.height;
//            newNode.type = "ruleGroup";
//            newNode.id = "rect" + StringUtils.generateShortUuid();
//            newNode.x = Integer.parseInt(cur.x) / 2 + "";
//            newNode.y = cur.y;
//            newNode.model = emptyRule.getManageId();
//            newNode.name = "规则集";
//            insertLine(cur, newNode, alLine);
//            newNodeList.add(newNode);
//        }
        alNode.addAll(newNodeList);
    }

    /**
     * 插入连接线
     *
     * @param cur     分支节点
     * @param newNode 新插入节点
     * @param alLine  当前连接线集合
     */
    private void insertLine(Node cur, Node newNode, List<Line> alLine) {
        Line newLine = new Line();
        newLine.from = newNode.id;
        newLine.to = cur.id;
        newLine.oriTo = newLine.to;
        //把所有指向当前分支节点的连接线，改为指向新插入节点
        for (Line ln : alLine) {
            if (ln.to.equals(cur.id)) {
                ln.to = newNode.id;
            }
        }
        alLine.add(newLine);

    }

    /**
     * 指定线段的开始节点是分支节点
     *
     * @param line   线段对象
     * @param alNode 节点对象
     * @return 如果起始节点是分支节点返回该节点，否则返回空值
     * @author ZengWenfeng
     * @date 2015.12.01
     */
    public Node isFork(Line line, ArrayList<Node> alNode) {
        if (alNode == null || alNode.size() <= 0) {
            return null;
        }

        for (int i = 0; i < alNode.size(); i++) {
            Node n = alNode.get(i);

            if (line.from.equals(n.id) && n.type.equals("fork")) {
                return n;
            }
        }

        return null;
    }
    
    public Node isChampion(String from, ArrayList<Node> alNode) {
    	if (from  == null) {
    		return  null;
    	}
        if (alNode == null || alNode.size() <= 0) {
            return null;
        }

        for (int i = 0; i < alNode.size(); i++) {
            Node n = alNode.get(i);

            if (from.equals(n.id) && n.type.equals("champion")) {
                return n;
            }
        }

        return null;
    }

    /**
     * 根据id查找节点集合的该节点
     *
     * @param alNode 节点对象
     * @return 如果存在，返回该节点；否则返回空值
     * @author ZengWenfeng
     * @date 2015.12.01
     */
    public Node getNodeById(String id, ArrayList<Node> alNode) {
        if (id == null || id.length() <= 0 || alNode == null || alNode.size() <= 0) {
            return null;
        }

        for (int i = 0; i < alNode.size(); i++) {
            Node n = alNode.get(i);

            if (id.equals(n.id)) {
                return n;
            }
        }

        return null;
    }

    /**
     * 计算
     *
     * @param a 第一个值
     * @param b 第二个值
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public String calcValue(String a, String b) {
        int c = Integer.parseInt(a);
        int d = Integer.parseInt(b);

        int e = c + d / 2;

        return Integer.toString(e);
    }

    /**
     * 根据给定的流程编码、版本号获取该流程能所有节点（除了开始、结束、分支、合并节点）所有信息
     * <p>
     * KEY          TYPE       VALUE code_version ------------------------------------------------------------
     * runflow_2.00 ruleFlow    ruleFlow_3.00 runflow_2.00 dataInit   dataInit_4.00 runflow_2.00
     * scoreModel scoreModel_sfdsfs ------------------------------------------------------------
     * runflow_4.00 ruleFlow    ruleFlow_5.00 runflow_4.00 dataInit   dataInit_7.00 runflow_4.00
     * scoreModel scoreModel_3 ------------------------------------------------------------
     *
     * @param code    规则流编码
     * @param version 版本
     * @return {流程编码_版本号：列表}
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public HashMap<String, List<SelectEditorVo>> getAllNodeInfo(String code, String version) {
        RuleFlowModel model = new RuleFlowModel();
        model.setCode(code);
        model.setVersion(version);

        //
        HashMap<String, List<SelectEditorVo>> hm = new HashMap<String, List<SelectEditorVo>>();

        //
        getNodeInfo(model, hm);

        //
        return hm;
    }

    /**
     * 获取流程图中节点信息
     *
     * @param model 工作流对象
     * @param hm    {流程编码_版本号：列表}
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public void getNodeInfo(RuleFlowModel model, HashMap<String, List<SelectEditorVo>> hm) {
        // 获取对象的xml内容
//		model = getByModelXml(model);
//
//		String keyCodeVersion = model.getCode() + RuleFlowModel.UNDERLINE + model.getVersion();
//		ArrayList<SelectEditorVo> list = new ArrayList<SelectEditorVo>();
//
//		String data = model.getData();
//		JSONObject jsonObj = JSONObject.parseObject(data);//转换成JSONObject
//
//		// ----------------------------------------------------------------------------------
//		// 01 解析states节点
//		// ----------------------------------------------------------------------------------
//		JSONObject states = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("states");
//		Collection<?> statesEntrys = states.entrySet();
//		Iterator<?> iStatesEntrys = statesEntrys.iterator();
//
//		// 开始遍历所有节点
//		Object objState = new Object();
//		while (iStatesEntrys.hasNext())
//		{
//			objState = iStatesEntrys.next();
//			if (objState == null)
//			{
//				continue;
//			}
//
//			String strState = objState.toString();
//
//			JSONObject state = JSONObject.parseObject(strState.substring(strState.indexOf("=") + 1));
//
//			String type = state == null ? null : state.getString("type");
//
//			// 不统计开始、结束、分支、合并节点、代码块
//			if (type.equals("start") || type.equals("end") || type.equals("join")||type.equals("codeblock"))
//			{
//				continue;
//			}
//
//			JSONObject objProps = state == null ? null : state.getJSONObject("props");
//			JSONObject key = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("model");
//			String value = key == null || key.isEmpty() ? null : key.getString("value");
//
//			// 如果是子流程节点，继续遍历子流程中的所有节点
//			if (type.equals("ruleFlow"))
//			{
//				String[] arrValue = value.split(RuleFlowModel.UNDERLINE);
//
//				model = new RuleFlowModel();
//				model.setCode(arrValue[0]);
//				model.setVersion(arrValue[1]);
//
//				//
//				getNodeInfo(model, hm);
//			} else if(type.equals("executionBlock")){
//				getExecutionBlockInfo(value,hm);
//			} else if(type.equals("fork")){
//				SelectEditorVo vo = new SelectEditorVo();
//				RuleCollectionVo ruleGroup = ruleSetService.getEmptyRuelSet();
//				vo.setName(ruleGroup.getType());
//				vo.setValue(ruleGroup.getCode()+"_"+ruleGroup.getVersion());
//				list.add(vo);
//			}
//			// 如果是其他节点，则记录该节点的信息
//			else
//			{
//				SelectEditorVo vo = new SelectEditorVo();
//				vo.setName(type);
//				vo.setValue(value);
//
//				list.add(vo);
//			}
//		}
//
//		hm.put(keyCodeVersion, list);
    }

    /**
     * 获取执行块信息
     *
     * @param value 规则流编码
     * @param hm    {流程编码_版本号：列表}
     */
    private void getExecutionBlockInfo(String value, HashMap<String, List<SelectEditorVo>> hm) {
//		ExecutionBlockModel model = executionBlockService.findModelByCode(value);
//		List<SelectEditorVo> list = new ArrayList<SelectEditorVo>();
//		for(ExecutionBlockNode n:model.getNodes()){
//			SelectEditorVo vo = new SelectEditorVo();
//			vo.setName(n.getType());
//			vo.setValue(n.getName()+"_"+n.getVersion());
//			list.add(vo);
//		}
//		hm.put(value, list);
    }

    /**
     * 读取json字符串
     *
     * @return String
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public String readJSONString(HttpServletRequest request) {
        StringBuffer str = new StringBuffer();
        String line = null;

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str.toString();
    }

    /**
     * 版本增加0.01
     *
     * @param version 当前版本号
     * @return 新版本号
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public String addOneInDecimal(String version) {
        if (version == null || version.trim().equals("")) {
            version = "0.00";
        }

        Double v = Double.parseDouble(version);
        v = v + 0.01;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        version = decimalFormat.format(v);
        return version;
    }

    /**
     * 版本增加1
     *
     * @param version 当前版本号
     * @return 新版本号
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public String addOneInInteger(String version) {
        if (version == null || version.trim().equals("")) {
            version = "0.00";
        }

        Double v = Double.parseDouble(version);
        Integer vi = (int) v.doubleValue();
        vi = vi + 1;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        version = decimalFormat.format(vi);
        return version;
    }

    /**
     * 根据给定的流程编码、版本号获取该流程能所有节点（除了开始、结束、分支、合并节点）所有信息
     * <p>
     * KEY          TYPE       VALUE code_version ------------------------------------------------------------
     * runflow_2.00 ruleFlow    ruleFlow_3.00 runflow_2.00 dataInit   dataInit_4.00 runflow_2.00
     * scoreModel scoreModel_sfdsfs ------------------------------------------------------------
     * runflow_4.00 ruleFlow    ruleFlow_5.00 runflow_4.00 dataInit   dataInit_7.00 runflow_4.00
     * scoreModel scoreModel_3 ------------------------------------------------------------
     *
     * @param code 规则流编码
     * @return {流程编码_版本号：列表}
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public HashMap<String, List<SelectEditorVo>> getAllNodeInfo(String code) {
        HashMap<String, List<SelectEditorVo>> hm = new HashMap<String, List<SelectEditorVo>>();
        this.getExecutionBlockInfo(code, hm);
        return hm;
    }

    /**
     * 重新生成bpmn文件，用于规则包生成
     *
     * @param code 格式：规则流编号_版本号
     */
    @Override
    public void reCreateBpmn(String code) throws Exception {

    }

    /**
     * 数组开头添加空值选项：--请选择--
     *
     * @param arr 旧数组 [{"name01", "value01"}, {"name02", "value02"}]
     * @return arrNew 新数组，第一项为空对象，其他项为旧数组对象 [{"--请选择--", ""}, {"name01", "value01"}, {"name02",
     * "value02"}]
     * @author ZengWenfeng
     * @date 2016.01.18
     */
    public SelectEditorVo[] addNullObject(SelectEditorVo[] arr) {
        //定义新数组的长度
        int length = 1;
        if (arr != null) {
            length += arr.length;
        }

        //定义新数组
        SelectEditorVo[] arrNew = new SelectEditorVo[length];

        //定义空对象
        SelectEditorVo vo = new SelectEditorVo();
        vo.setName("--请选择--");
        vo.setValue("");

        //新数组第一个元素设置为空对象
        arrNew[0] = vo;

        //遍历旧数组，把旧数组的所有元素添加到新数组中
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                arrNew[i + 1] = arr[i];
            }
        }

        //返回新数组
        return arrNew;
    }

    /**
     * 发布版本
     */
    public void updateVersion(RuleManage ruleManage) throws BizException {
        RuleFlow ruleFlow = new RuleFlow();
        if (ruleManage.getOldId() != null) {
        	ruleFlow.setManageId(ruleManage.getOldId());
        	ruleFlow.setVersion(ruleManage.getOldVersion());
        } else {
        	ruleFlow.setManageId(ruleManage.getId());
        	ruleFlow.setVersion(ruleManage.getOldVersion());
        }
        List<RuleFlow> list = this.findList(ruleFlow);
        RuleFlow flow = null;
        if (list.size() > 0) {
            flow = list.get(0);
            flow.setId(null);
            flow.setManageId(ruleManage.getId());
            flow.setVersion(ruleManage.getVersion());
            this.save(flow);
        }

        RuleFlowRects rectCon = new RuleFlowRects();
        rectCon.setManageId(ruleFlow.getManageId());
        rectCon.setVersion(ruleFlow.getVersion());
        List<RuleFlowRects> rectList = ruleFlowRectsService.findList(rectCon);
        //查找老版本冠军挑战者信息
        Collection<RuleReferenceData> championList = ruleReferenceDataService.findReferenceChampionList(rectCon);
        //将库中冠军挑战者信息CV给新发布版本
        Map<String, RuleReferenceData> championParam = new HashMap();
        String attr = "";
        for (RuleReferenceData insertChampion : championList) {
        	String controlValue = insertChampion.getClassName();
        	if(controlValue == null) continue;
        	attr = insertChampion.getClassName();
			ruleReferenceDataService.collectCommonData(insertChampion, attr, "in", ruleManage, championParam);
			this.ruleReferenceDataService.saveReferenceData(championParam);
        }
        
        RuleFlowConditions rectConditions = new RuleFlowConditions();
        rectConditions.setManageId(ruleFlow.getId());
        rectConditions.setVersion(ruleFlow.getVersion());
        List<RuleFlowConditions> rectConList = ruleFlowConditionsService.findList(rectConditions);
        //收集引用数据
        Map<String, RuleReferenceData> refMap = new HashMap();
        String key = "";
        for (RuleFlowConditions condition : rectConList) {
        	String controlValue = condition.getControlValues();
        	if(controlValue != null) {
	        	if (controlValue.startsWith("{") && controlValue.endsWith("}")) {
					controlValue=StringUtils.replace(controlValue, "￥", "\"");
					try {
						Map<String, String> controlMap = (new ObjectMapper()).readValue(controlValue, Map.class);
						key = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
						ruleReferenceDataService.collectFromMap(controlMap, key, "in", ruleManage, refMap);
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				}
        	}
			key = condition.getClassName() + "|" + condition.getNameen() + "|in";
			ruleReferenceDataService.collectCommonData(condition, key, "in", ruleManage, refMap);
			
        }
        //保存数据数据
        this.ruleReferenceDataService.saveReferenceData(refMap);

        ruleFlowRectsService.insertBatch(rectList, new String[]{"id", "manageId", "projectCode", "version"},
                new Object[]{null, ruleManage.getId(), ruleManage.getProjectCode(), ruleManage.getVersion()}, true);
        if (rectConList.size() > 0) {
            ruleFlowConditionsService.insertBatch(rectConList, new String[]{"id", "manageId", "projectCode", "version"},
                    new Object[]{null, ruleManage.getId(), ruleManage.getProjectCode(), ruleManage.getVersion()}, true);
        }
    }

    /**
     * 模型复制
     */
    @Override
    public void copyRule(RuleManage oldRuleManage, RuleManage ruleManage) throws BizException {
        ruleManage.setOldVersion(oldRuleManage.getVersion());
        ruleManage.setOldId(oldRuleManage.getId());
        this.updateVersion(ruleManage);
    }

    @Override
    public List<RuleVersioninfo> findRuleFlowPublishVersion(String projectCode, String code, String version) throws BizException {
        List<RuleVersioninfo> results = new ArrayList();
        RuleManage ruleInfo = new RuleManage();
        ruleInfo.setCode(code);
        ruleInfo.setVersion(version);
        ruleInfo.setProjectCode(projectCode);
        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
        if (list == null || list.size() == 0) {
            throw new BizException("E-000600");
        }
        RuleManage ruleManage = list.get(0);
        Map<String, RuleVersioninfo> map = this.findRuleFlowPublishVersion(projectCode, code, version, null);
        for (String key : map.keySet()) {
            results.add(map.get(key));
        }

        // 生成规则流
        RuleVersioninfo bpmVersion = new RuleVersioninfo();
        bpmVersion.setManageId(ruleManage.getId());
        bpmVersion.setVersion(version);
        List<RuleVersioninfo> bpmRuleList = this.ruleVersioninfoService.findPublishVersionList(bpmVersion);
        results.addAll(bpmRuleList);
        return results;
    }
    /**
     * 查找规则流，各个节点引用模型的生效版本
     * @param projectCode
     * @param code
     * @param version
     * @param vMap
     * @return
     * @throws BizException
     */
    private Map<String, RuleVersioninfo> findRuleFlowPublishVersion(String projectCode, String code, String version, Map<String, RuleVersioninfo> vMap) throws BizException {
        if ( vMap == null ) {
            vMap = new HashMap();
        }
        Map<String, RuleVersioninfo> results = vMap;
        //查找当前规则流版本对应的ruleManage
        RuleManage ruleInfo = new RuleManage();
        ruleInfo.setCode(code);
        ruleInfo.setVersion(version);
        ruleInfo.setProjectCode(projectCode);
        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
        if (list == null || list.size() == 0) {
            throw new BizException("E-000600");
        }
        RuleManage ruleManage = list.get(0);
        //查找规则流的全部节点
        RuleFlowRects flowRectsInfo = new RuleFlowRects();
        flowRectsInfo.setManageId(ruleManage.getId());
        flowRectsInfo.setVersion(version);
        List<RuleFlowRects> rects = this.ruleFlowRectsService.findList(flowRectsInfo);
        RuleVersioninfo versionInfo = null;
        List<RuleVersioninfo> verList = null;
        String rcode = null;
        String rversion = null;
        //循环，判断获取各个模型的版本
        for (RuleFlowRects ruleFlowRects : rects) {
            if (!StringUtils.isEmpty(ruleFlowRects.getRectCode())) {
                rcode = ruleFlowRects.getRectCode();
                rversion = ruleFlowRects.getRectVersion();
                String rectType = ruleFlowRects.getRectType();
                if("func".equalsIgnoreCase(rectType)) {
                	continue;
                }
                if("emptysetforupdate".equals(rcode)) {
                	try {
						RuleVersioninfo emptyRule = ruleVersioninfoService.getEmptyRuelSet();
						if(verList==null)
							verList = new ArrayList<RuleVersioninfo>();
						verList.add(emptyRule);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }else {
                	//根据生效版本去查找
                	RuleManage eacherm = ruleManageService.findByCode(rcode, projectCode);
                    versionInfo = new RuleVersioninfo();
                    versionInfo.setModelCode(rcode);
                    versionInfo.setVersion(eacherm.getActiveVersion());
                    versionInfo.setProjectCode(projectCode);
                    verList = this.ruleVersioninfoService.findPublishVersionList(versionInfo);
                    //verList = this.ruleVersioninfoService.findCurrVerList(versionInfo);
                }
                for (RuleVersioninfo ruleVersioninfo : verList) {
                    results.put(ruleVersioninfo.getManageId() + ruleVersioninfo.getVersion(), ruleVersioninfo);
                    break;
                }
                if ("executionblock".equals(rectType.toLowerCase())||("policyRuleGroup".equals(rectType)||rcode.startsWith("EXN"))) {//执行块
                    RuleManage tmpRuleManage = this.ruleManageService.findByCode(rcode, projectCode);
                    if (tmpRuleManage != null ) {
                        RuleExcutionBlock excutionBlock = new RuleExcutionBlock();
                        excutionBlock.setManageId(tmpRuleManage.getId());
                        excutionBlock.setBlockVersion(tmpRuleManage.getVersion());
                        List<RuleExcutionBlock> bList = this.ruleExcutionBlockDao.findList(excutionBlock);
                        for (RuleExcutionBlock ruleExcutionBlock : bList) {
                        	String execcode = ruleExcutionBlock.getExecCode();
                        	if(execcode.length()==32)continue;
                        	RuleManage rm = this.ruleManageService.findByCode(ruleExcutionBlock.getExecCode(), projectCode);
                            versionInfo = new RuleVersioninfo();
                            versionInfo.setModelCode(rm.getCode());
                            versionInfo.setVersion(rm.getActiveVersion());
                            versionInfo.setProjectCode(projectCode);
                            verList = this.ruleVersioninfoService.findPublishVersionList(versionInfo);
                            for (RuleVersioninfo ruleVersioninfo : verList) {
                                results.put(ruleVersioninfo.getManageId() + ruleVersioninfo.getVersion(), ruleVersioninfo);
                            }
                        }
                    }
                } else if ("ruleFlow".equals(rectType) || "strategyFlow".equals(rectType)) {//子流程
                    this.findRuleFlowPublishVersion(projectCode, rcode, rversion, results);
                }

            }
        }
        return results;
    }
    
    private Map<String, String> findRuleFlowRefeVersion(String projectCode, String code, String version, Map<String, String> vMap) throws BizException {
        if (vMap == null)
            vMap = new HashMap();
        Map<String, String> results = vMap;
        RuleManage ruleInfo = new RuleManage();
        ruleInfo.setCode(code);
        ruleInfo.setVersion(version);
        ruleInfo.setProjectCode(projectCode);
        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
        if (list == null || list.size() == 0) {
            throw new BizException("E-000600");
        }
        RuleManage ruleManage = list.get(0);
        RuleFlowRects flowRectsInfo = new RuleFlowRects();
        flowRectsInfo.setManageId(ruleManage.getId());
        flowRectsInfo.setVersion(version);
        List<RuleFlowRects> rects = this.ruleFlowRectsService.findList(flowRectsInfo);
        List<RuleVersioninfo> verList = null;
        String rcode = null;
        String rversion = null;
        for (RuleFlowRects ruleFlowRects : rects) {
            if (!StringUtils.isEmpty(ruleFlowRects.getRectCode())) {
                rcode = ruleFlowRects.getRectCode();
                rversion = ruleFlowRects.getRectVersion();
                String rectType = ruleFlowRects.getRectType();
                
                if ("decisionTree".equals(rectType)) {
                   Map<String,String>  varMap  = new HashMap<String,String>();
                   varMap.put("code", rcode);
                   varMap.put("projectCode", projectCode);
                   
                   List<String> strList =this.ruleVersioninfoService.findRuleRefeCodes(varMap);
                   if (strList ==null || strList.size() <1) {
                	   continue;
                   }
                   Map<String,Object>  vrMap = new  HashMap<String,Object>();
                   vrMap.put("projectCode", projectCode);
                   vrMap.put("refeList", strList);
                   verList=this.ruleVersioninfoService.findRuleRefeVersion(vrMap);
                   for (RuleVersioninfo ruleVersioninfo : verList) {
                       results.put(ruleVersioninfo.getModelCode(), ruleVersioninfo.getRuleContent());
                      
                   }
                }
                    //verList = this.ruleVersioninfoService.findCurrVerList(versionInfo);
//                for (RuleVersioninfo ruleVersioninfo : verList) {
//                    results.put(ruleVersioninfo.getModelCode(), ruleVersioninfo.getRuleContent());
//                   
//                }
                if ("ruleFlow".equals(rectType)) {//子流程
                    this.findRuleFlowRefeVersion(projectCode, rcode, rversion, results);
                }

            }
        }
        return results;
    }
    
    
    public   Map<String,String>  findRuleRefeVersion(String projectCode, String code, String version) throws BizException {
        RuleManage ruleInfo = new RuleManage();
        ruleInfo.setCode(code);
        ruleInfo.setVersion(version);
        ruleInfo.setProjectCode(projectCode);
        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
        if (list == null || list.size() == 0) {
            throw new BizException("E-000600");
        }
        RuleManage ruleManage = list.get(0);
        Map<String, String> map = this.findRuleFlowRefeVersion(projectCode, code, version, null);
 

        // 生成规则流
        RuleVersioninfo bpmVersion = new RuleVersioninfo();
        bpmVersion.setManageId(ruleManage.getId());
        bpmVersion.setVersion(version);
        List<RuleVersioninfo> bpmRuleList = this.ruleVersioninfoService.findPublishVersionList(bpmVersion);
        for (RuleVersioninfo ruleVer:bpmRuleList) {
        	map.put(ruleVer.getModelCode(), ruleVer.getRuleContent());
        }
        return map;
    }

	@Override
	public Map<String, String> findRuleRefeVerByProjectCode(String projectCode) throws BizException {
		// TODO Auto-generated method stub
		return this.ruleVersioninfoService.findProjectRefeVersion(projectCode);
	}

	@Override
	public List<SelectEditorVo> getAllVersion(RuleVersioninfo ruleVersioninfo) throws BizException {
        List<RuleVersioninfo> verlist = ruleVersioninfoService.findPublishVersionList(ruleVersioninfo);

        List<SelectEditorVo> list = new ArrayList();
        for (RuleVersioninfo ruleVer : verlist) {
            String value = ruleVer.getModelCode() + "_" + ruleVer.getVersion();
            String name = ruleVer.getModelName() + "_" + ruleVer.getVersion();
            String version = ruleVer.getVersion().replace("v", "");
            SelectEditorVo select = new SelectEditorVo(ruleVer.getManageId(),name, value, Double.valueOf(version));
            list.add(select);
        }
        return list;
	}
	
	  public  List<String>  findRuleFlowRefeList(String projectCode, String code, String version) throws BizException{
		    Map<String,String> retMap  = new  HashMap<>();
		    Map<String,String> res=  this.findRuleFlowRefeCodes(projectCode, code, version, retMap);
		    Set<String> set =res.keySet();
		    List<String> reList  = new ArrayList<>();
		    for (String refCode:set) {
		    	reList.add(refCode);
		    }
		    return  reList;
		    
	  }
	
	  private Map<String, String> findRuleFlowRefeCodes(String projectCode, String code, String version, Map<String, String> vMap) throws BizException {
	        if (vMap == null)
	            vMap = new HashMap();
	        Map<String, String> results = vMap;
	        RuleManage ruleInfo = new RuleManage();
	        ruleInfo.setCode(code);
	        ruleInfo.setVersion(version);
	        ruleInfo.setProjectCode(projectCode);
	        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
	        if (list == null || list.size() == 0) {
	            throw new BizException("E-000600");
	        }
	        RuleManage ruleManage = list.get(0);
	        RuleFlowRects flowRectsInfo = new RuleFlowRects();
	        flowRectsInfo.setManageId(ruleManage.getId());
	        flowRectsInfo.setVersion(version);
	        List<RuleFlowRects> rects = this.ruleFlowRectsService.findList(flowRectsInfo);
	        List<RuleVersioninfo> verList = null;
	        String rcode = null;
	        String rversion = null;
	        for (RuleFlowRects ruleFlowRects : rects) {
	            if (!StringUtils.isEmpty(ruleFlowRects.getRectCode())) {
	                rcode = ruleFlowRects.getRectCode();
	                rversion = ruleFlowRects.getRectVersion();
	                String rectType = ruleFlowRects.getRectType();
	                
	                if ("decisionTree".equals(rectType)) {
	                   Map<String,String>  varMap  = new HashMap<String,String>();
	                   varMap.put("code", rcode);
	                   varMap.put("projectCode", projectCode);
	                   List<String>  codes = this.ruleVersioninfoService.findRuleRefeCodes(varMap);
	                   for (String  cds:codes) {
	                	   results.put(cds, cds);
	                   }

	                }

	                if ("ruleFlow".equals(rectType)) {//子流程
	                    this.findRuleFlowRefeVersion(projectCode, rcode, rversion, results);
	                }

	            }
	        }
	        return results;
	    }


	public List<RuleNextTreeNode> findTreeClassType(String projectCode, String treeCode) {
		List<RuleNextTreeNode>  result   = new  ArrayList<>();
		Map<String,String>  map  = new  HashMap<String,String>();
		map.put("projectCode", projectCode);
		map.put("treeCode", treeCode);
		List<String>  rList =this.dao.findTreeClassType(map);
		Map<String,String> rmap  = new  HashMap<>();
		for (String  str:rList) {
			rmap.put(str, str);
		}
		RuleNextTreeNode  nextTreeNode  = null;
		for (String  type:rmap.values()) {
			if (type !=null && !type.equals("")) {
			   nextTreeNode  = new  RuleNextTreeNode(type,"","");
		 	   result.add(nextTreeNode);
			}
		}
		result.add(new RuleNextTreeNode("otherwise","",""));
		return  result;
	}


	@Override
	public void clearVersion(RuleManage ruleManage,List<String> versions) {
		if(versions!=null&&versions.size()>0) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("projectCode", ruleManage.getProjectCode());
			map.put("manageId", ruleManage.getId());
			map.put("versions", versions);
			this.dao.deleteByMutilVersion(map);
			this.ruleFlowConditionsService.deleteByMutilVersion(map);
			this.ruleFlowRectsService.deleteByMutilVersion(map);
		}
	}


	@Override
	public void updateSetParam(String manageId, RuleSetParamInfo newSetParamInfo,RuleSetParamInfo oldParamInfo, boolean setFlag) throws Exception {
          RuleFlow  ruleFlow  = new  RuleFlow();
          ruleFlow.setManageId(manageId);
          RuleManage ruleManage = this.ruleManageService.get(manageId);
		  List<RuleFlow> list = this.dao.findList(ruleFlow); 
		  if (list != null &&  list.size()>0) {
			  RuleFlow  tmpFlow  =  list.get(0);
		      JSONObject jsonObj = JSONObject.parseObject(tmpFlow.getRuleflowInfo());//转换成JSONObject
		      if (jsonObj == null) {
		            return ;
		      }
		      JSONObject paths = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("paths");
		      
		     Set<String> keys = paths.keySet();
		     boolean  flag  = false;
		     for  (String  key :keys) {
		    	 JSONObject path = paths.getJSONObject(key);
		    	 if (path != null) {
		    		 JSONObject props= path.getJSONObject("props");
		    		 if (props== null)  continue;
		    		 JSONObject  constaint = props.getJSONObject("constaints");
		    		 if (constaint != null) {
		    			    String popConstaint = constaint.getString("value");
		    			 
							String tmpItemStr =popConstaint.replace("@", "\"");
							if (!StringUtils.isEmpty(tmpItemStr)) {
								List<RuleFlowItem> itemList =JSON.parseArray(tmpItemStr, RuleFlowItem.class);
								if (itemList !=null  ) {
									for  (RuleFlowItem conFlowItem:itemList) {
 								         String  conValue =	conFlowItem.getControlValue().replace("%", "\"");
 							  			 if (setFlag) {
 							  				 if (oldParamInfo.getCode().equals(conFlowItem.getClassName())) {
 							  					flag  = true; 
 							  					conFlowItem.setClassName(newSetParamInfo.getCode());
 							  				 }
 							  			
 										 }else {
 											if (oldParamInfo.getCode().equals(conFlowItem.getNameEN())) {
 	 											conFlowItem.setNameEN(newSetParamInfo.getCode());
 	 											conFlowItem.setNameCN(newSetParamInfo.getName());
 	 											flag  = true;
 											}

 										 }
 										if (conValue.startsWith("{") && conValue.endsWith("}")) {
 											conValue=StringUtils.replace(conValue, "￥", "\"");
											Map<String, String> controlMap = (new ObjectMapper()).readValue(conValue, Map.class);
											if (setFlag) {
												if (oldParamInfo.getCode().equals(controlMap.get("className"))) {
													controlMap.put("className", newSetParamInfo.getCode());
												}
												
											}else {
												if (oldParamInfo.getCode().equals(controlMap.get("nameEN"))) {
													controlMap.put("nameEN", newSetParamInfo.getCode());
													controlMap.put("nameCN", newSetParamInfo.getName());													
												}
												
											}
											String  contrlValue =JSON.toJSONString(controlMap);
											contrlValue=StringUtils.replace(contrlValue, "\"", "￥");
											conFlowItem.setControlValue(contrlValue.replace("\"", "%"));
 										}	
 					                     
									}
									String  condStr =JSON.toJSONString(itemList);
									String  value =condStr.replaceAll("\"", "@");
									constaint.put("value", value);
									
								}
								
							}
		    			 
		    		 }
		    		
		    	 }
		     }
		     if (!flag) return;

		     List<Map<String, String>> championInfo = new ArrayList<>();
		     String  context = this.buildBpmn(jsonObj, ruleManage, championInfo);
		     tmpFlow.setRuleflowInfo(JSONObject.toJSONString(jsonObj));
		     this.save(tmpFlow);
	   		 RuleVersioninfo  versInfo  = new RuleVersioninfo();
		   	 versInfo.setManageId(ruleManage.getId());
		   	 versInfo.setVersion(ruleManage.getActiveVersion());
		   	 List<RuleVersioninfo> vList =	this.ruleVersioninfoService.findList(versInfo);
		   	 if (vList != null && vList.size()>0) {
		   	    	RuleVersioninfo  ruleVer = vList.get(0);
		   	    	ruleVer.setRuleContent(context);
		   	    	this.ruleVersioninfoService.save(ruleVer);
		   	 }
			  
		  }
	}
    
	
	 
    private  String  buildBpmn(JSONObject jsonObj,RuleManage ruleManage,List<Map<String, String>> championInfo ) throws Exception {
        // ----------------------------------------------------------------------------------
        // 01 解析states节点
        // ----------------------------------------------------------------------------------
        JSONObject states = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("states");
        Collection<?> statesEntrys = states.entrySet();
        Iterator<?> iStatesEntrys = statesEntrys.iterator();
        // 保存所有节点
        ArrayList<Node> alNode = new ArrayList<Node>();
        Map<String,Node> alNodeMap = new HashMap<String,Node>();
        Object objState = new Object();
        while (iStatesEntrys.hasNext()) {
            objState = iStatesEntrys.next();
            if (objState == null) {
                continue;
            }
            String strState = objState.toString();
            String id = strState.substring(0, strState.indexOf("="));
            JSONObject state = JSONObject.parseObject(strState.substring(strState.indexOf("=") + 1));
            String type = state == null ? null : state.getString("type");
            JSONObject objAttr = state == null ? null : state.getJSONObject("attr");
            String x = objAttr == null ? null : objAttr.getString("x");
            String y = objAttr == null ? null : objAttr.getString("y");
            String width = objAttr == null ? null : objAttr.getString("width");
            String height = objAttr == null ? null : objAttr.getString("height");

            JSONObject objProps = state == null ? null : state.getJSONObject("props");
            JSONObject objProps01 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("constaints");
            JSONObject objProps02 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("name");
            JSONObject objProps03 = objProps == null || objProps.isEmpty() ? null : objProps.getJSONObject("model");
            String strProps01 = objProps01 == null || objProps01.isEmpty() ? null : objProps01.getString("value");
            String strProps02 = objProps02 == null || objProps02.isEmpty() ? null : objProps02.getString("value");
            String strProps03 = objProps03 == null || objProps03.isEmpty() ? null : objProps03.getString("value");

            Node n = new Node();
            n.id = id;
            n.type = type;
            n.x = x;
            n.y = y;
            n.width = width;
            n.height = height;
            n.constaints = strProps01;
            n.name = strProps02;
            n.model = strProps03;
            alNode.add(n);
            alNodeMap.put(n.id, n);
        }
        // ----------------------------------------------------------------------------------
        // 02 解析paths连线
        // ----------------------------------------------------------------------------------
        JSONObject paths = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("paths");
        Collection<?> pathsEntrys = paths.entrySet();
        Iterator<?> iPaths = pathsEntrys.iterator();
        // 保存所有节点
        ArrayList<Line> alLine = new ArrayList<Line>();
        Object objPath = new Object();
        while (iPaths.hasNext()) {
            objPath = iPaths.next();
            if (objPath == null) {
                continue;
            }
            String strPath = objPath.toString();
            String id = strPath.substring(0, strPath.indexOf("="));
            JSONObject path = JSONObject.parseObject(strPath.substring(strPath.indexOf("=") + 1));
            //"path8":{"from":"rect1commato":"rect4commadots":[],"text":{"text":"TO 分支"},"textPos":{"x":0,"y":-10},"props":{"text":{"value":""}}},
            String from = path.getString("from");
            String to = path.getString("to");
            String strDots = "";
            JSONArray dots = path.getJSONArray("dots");
            if (dots != null && dots.size() > 0) {
                for (int i = 0; i < dots.size(); i++) {
                    Object xy = dots.get(i);
                    JSONObject objXy = JSONObject.parseObject(JSONObject.toJSONString(xy));

                    String objXy_x = objXy.getString("x");
                    String objXy_y = objXy.getString("y");

                    strDots += objXy_x + comma + objXy_y + semicolon;
                }
            }

            if (strDots.length() > 0) {
                strDots = strDots.substring(0, strDots.length() - 1);
            }

            JSONObject text = path.getJSONObject("text");
            String text_text = text.getString("text");

            JSONObject textPos = path.getJSONObject("textPos");
            String x = textPos.getString("x");
            String y = textPos.getString("y");

            JSONObject props = path.getJSONObject("props");
            JSONObject props_text = props.getJSONObject("text");
            String value = props_text.getString("value");

            JSONObject props_constaints = props.getJSONObject("constaints");
            String constaints = props_constaints==null?null:props_constaints.getString("value");
            
            
            Line line = new Line();
            line.id = id;
            line.from = from;
            line.to = to;
            line.dots = strDots;
            line.text = text_text;
            line.x = x;
            line.y = y;
            line.value = value;
            line.constaints = constaints;
            alLine.add(line);
        }
        // ----------------------------------------------------------------------------------
        // 03 解析props节点
        // ----------------------------------------------------------------------------------
        JSONObject props = jsonObj.isEmpty() ? null : jsonObj.getJSONObject("props");
        JSONObject props_props = props.getJSONObject("props");

        //
        JSONObject props_name = props_props == null ? null : props_props.getJSONObject("name");
        JSONObject props_flag = props_props == null ? null : props_props.getJSONObject("flag");
        JSONObject props_pack = props_props == null ? null : props_props.getJSONObject("pack");
        JSONObject props_lane = props_props == null ? null : props_props.getJSONObject("lane");
        JSONObject props_itemDefinition = props_props == null ? null : props_props.getJSONObject("itemDefinition");
        JSONObject props_version = props_props == null ? null : props_props.getJSONObject("version");

        String strFlag = props_name == null ? null : props_name.getString("value");
        String strName = props_flag == null ? null : props_flag.getString("value");
        String strPack = props_pack == null ? null : props_pack.getString("value");
        String strLane = props_lane == null ? null : props_lane.getString("value");
        String strItemDefinition = props_itemDefinition == null ? null : props_itemDefinition.getString("value");
        String strVersion = props_version == null ? null : props_version.getString("value");

        // ----------------------------------------------------------------------------------
        // 04 生成文件
        // ----------------------------------------------------------------------------------
        insertUpdateNode(alNode, alLine);//分支节点前插入一个空节点以执行同步动作
        String space = "    ";
        String wrap = "\n";

        StringBuffer content = new StringBuffer();
        content.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + wrap);
        content.append("<definitions id=\"Definition\"" + wrap);
        content.append(space + "targetNamespace=\"http://www.jboss.org/drools\"" + wrap);
        content.append(space + "typeLanguage=\"http://www.java.com/javaTypes\"" + wrap);
        content.append(space + "expressionLanguage=\"http://www.mvel.org/2.0\"" + wrap);
        content.append(space + "xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"" + wrap);
        content.append(space + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + wrap);
        content.append(space + "xsi:schemaLocation=\"http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd\"" + wrap);
        content.append(space + "xmlns:g=\"http://www.jboss.org/drools/flow/gpd\"" + wrap);
        content.append(space + "xmlns:bpmndi=\"http://www.omg.org/spec/BPMN/20100524/DI\"" + wrap);
        content.append(space + "xmlns:dc=\"http://www.omg.org/spec/DD/20100524/DC\"" + wrap);
        content.append(space + "xmlns:di=\"http://www.omg.org/spec/DD/20100524/DI\"" + wrap);
        content.append(space + "xmlns:tns=\"http://www.jboss.org/drools\">" + wrap);
        content.append(wrap);

        if (strItemDefinition != null) {
            if (strItemDefinition.indexOf(semicolon) >= 0) {
                String[] arrItem = strItemDefinition.split(semicolon);
                for (int i = 0; i < arrItem.length; i++) {
                    String curItem = arrItem[i];
                    if (curItem.indexOf(comma) >= 0) {
                        String[] itemDefinitionProps = curItem.split(comma);
                        content.append(space + "<itemDefinition id=\"_" + itemDefinitionProps[0] + "Item" + "\" structureRef=\"" + itemDefinitionProps[1] + "\"/>" + wrap);
                    }
                }
            } else {
                if (strItemDefinition.indexOf(comma) >= 0) {
                    String[] itemDefinitionProps = strItemDefinition.split(comma);
                    //<itemDefinition id="_theStutasItem" structureRef="Boolean" />
                    content.append(space + "<itemDefinition id=\"_" + itemDefinitionProps[0] + "Item" + "\" structureRef=\"" + itemDefinitionProps[1] + "\"/>" + wrap);
                }
            }
            content.append(wrap);
        }
        strFlag = ruleManage.getCode();
        strPack = "com.tansun.policyrulegroup";
        if (strVersion == null || strVersion.length() < 0) {
            strVersion = ruleManage.getActiveVersion();
        }
//        content.append(space + "<process processType=\"Private\" isExecutable=\"true\" id=\"" + strFlag + "_" + model.getVersion() + "\" name=\"" + strName + "\" tns:packageName=\"" + strPack + "\" tns:version=\"" + strVersion + "\">" + wrap);
        content.append(space + "<process processType=\"Private\" isExecutable=\"true\" id=\"" + strFlag + "\" name=\"" + ruleManage.getName() + "\" tns:packageName=\"" + strPack + "\" tns:version=\"" + strVersion + "\">" + wrap);

        content.append(space + space + "<extensionElements>" + wrap);
        content.append(space + space + space + "<tns:import name=\"java.util.*\"/>" + wrap);
        content.append(space + space + space + "<tns:import name=\"com.tansun.rule.utils.*\" />" + wrap);
        content.append(space + space + space + "<tns:import name=\"com.tansun.ruledata.data.dao.DataMiningDao\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"ruleHelper\" type=\"com.tansun.rule.utils.RuleHelper\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"droolsRuleLog\" type=\"com.tansun.rule.utils.DroolsRuleLog\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"dataMap\" type=\"java.util.Map\" />" + wrap);
        content.append(space + space + space + "<tns:global identifier=\"metaMap\" type=\"java.util.Map\" />" + wrap);
        content.append(space + space + "</extensionElements>" + wrap);
        if (strItemDefinition != null) {
            content.append(space + space + "<!-- process variables -->" + wrap);
            if (strItemDefinition.indexOf(semicolon) >= 0) {
                String[] arrItem = strItemDefinition.split(semicolon);
                for (int i = 0; i < arrItem.length; i++) {
                    String curItem = arrItem[i];
                    if (curItem.indexOf(comma) >= 0) {
                        String[] ItemDefinitionProps = curItem.split(comma);
                        content.append(space + space + "<property id=\"" + ItemDefinitionProps[0] + "\" itemSubjectRef=\"_" + ItemDefinitionProps[0] + "Item" + "\"/>" + wrap);
                    }
                }
            } else {
                if (strItemDefinition.indexOf(comma) >= 0) {
                    String[] ItemDefinitionProps = strItemDefinition.split(comma);
                    content.append(space + space + "<property id=\"" + ItemDefinitionProps[0] + "\" itemSubjectRef=\"_" + ItemDefinitionProps[0] + "Item" + "\"/>" + wrap);
                }
            }
        }
        content.append(wrap);
        if (strLane != null && strLane.length() > 0) {
            content.append(space + space + "<laneSet>" + wrap);
            if (strLane.indexOf(semicolon) >= 0) {
                String[] arrLaneProp = strLane.split(semicolon);
                for (int i = 0; i < arrLaneProp.length; i++) {
                    content.append(space + space + space + "<lane name=\"" + arrLaneProp[i] + "\"></lane>" + wrap);
                }
            } else {
                content.append(space + space + space + "<lane name=\"" + strLane + "\"></lane>" + wrap);
            }
            content.append(space + space + "</laneSet>" + wrap);
            content.append(wrap);
            content.append(space + space + "<!-- nodes -->" + wrap);
            List<Node> nodeList = new ArrayList<Node>();
            // 遍历节点
            if (alNode != null && alNode.size() > 0) {
                for (int i = 0; i < alNode.size(); i++) {
                    Node curNode = alNode.get(i);
                    nodeList.add(curNode);
                    if (curNode.type != null) {
                        if (curNode.type.equals("start")) {
                            content.append(space + space + "<startEvent id=\"" + curNode.id + "\"/>" + wrap);
                        } else if (curNode.type.equals("end")) {
                            content.append(space + space + "<endEvent id=\"" + curNode.id + "\" name=\"" + curNode.name + "\"/>" + wrap);
                        } else if (curNode.type.equals("task")) {
                            content.append(space + space + "<businessRuleTask id=\"" + curNode.id + "\" name=\"" + curNode.name + "\">" + wrap);
                        } else if (curNode.type.equals("codeblock") || curNode.type.equals("dataComponent")) {
                            content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                            String codeSc = null;
                            if (curNode.type.equals("codeblock")) {
                                codeSc = StringEscapeUtils.escapeXml10(ruleCodeblockService.findCodeblocksByCode(curNode.model, ruleManage.getProjectCode()));
                            } else {
                                //找数据源的代码
                                String[] arr = curNode.model.split("_");
                                RuleManage dcManage = ruleManageService.findByCode(arr[0], ruleManage.getProjectCode());
                                RuleVersioninfo con = new RuleVersioninfo();
                                con.setManageId(dcManage.getId());
                                con.setVersion(arr[1]);
                                List<RuleVersioninfo> list = ruleVersioninfoService.findList(con);
                                codeSc = StringEscapeUtils.escapeXml10(list.get(0).getRuleContent());
                            }
                            if (codeSc == null)
                                codeSc = "";
                            content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        } else if (curNode.type.equals("func")) {
                            content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                            String codeSc = curNode.model+"(dataMap,metaMap);";
                            content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        } else if (curNode.type.equals("fork")) {
                            content.append(space + space + "<inclusiveGateway id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" gatewayDirection=\"Diverging\"/>" + wrap);
                        } else if (curNode.type.equals("join")) {
                            content.append(space + space + "<exclusiveGateway id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" gatewayDirection=\"Converging\"/>" + wrap);
                        } else if (curNode.type.equals("ruleFlow") || curNode.type.equals("executionBlock") ) {
                        	content.append(space + space + "<callActivity id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" calledElement=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</callActivity>" + wrap);
                        }else if (curNode.type.equals("champion")) {
                        	
                        }                        
                        else if ("policyRuleGroup".equals(curNode.type) && curNode.model!=null && curNode.model.startsWith("EXN")) {
                        	RuleManage rm = ruleManageService.findByCode(curNode.model, ruleManage.getProjectCode());
                            content.append(space + space + "<callActivity id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" calledElement=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</callActivity>" + wrap);
                        }else if(curNode.type.equals("bigdata")){
                        	String codeSc = "System.out.println(\""+curNode.name+"\");";
                        	content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                        	content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        }else if(curNode.type.equals("datamining")){
                        	String codeSc = "droolsRuleLog.addLogs(\""+curNode.model+"\", \"datamining\", \""+curNode.model+ "\", \""+curNode.model+ "\", \""+curNode.model+ "\", 1);\r\n";
                        	codeSc += "DataMiningDao.evaluatePmml(\""+curNode.model+"\",\""+ruleManage.getProjectCode()+"\",dataMap);";
                        	content.append(space + space + "<scriptTask id=\"" + curNode.id + "\" name=\"Script\" scriptFormat=\"http://www.java.com/java\">" + wrap);
                        	content.append(space + space + space + "<script>" + codeSc + "\r\n" + "</script>" + wrap);//脚本执行以换行符结束
                            content.append(space + space + "</scriptTask>" + wrap);
                        }else {
                            content.append(space + space + "<businessRuleTask id=\"" + curNode.id + "\" name=\"" + curNode.name + "\" g:ruleFlowGroup=\"" + curNode.model + "\">" + wrap);
                            content.append(space + space + space + "<ioSpecification>" + wrap);
                            content.append(space + space + space + space + "<inputSet>" + wrap);
                            content.append(space + space + space + space + "</inputSet>" + wrap);
                            content.append(space + space + space + space + "<outputSet>" + wrap);
                            content.append(space + space + space + space + "</outputSet>" + wrap);
                            content.append(space + space + space + "</ioSpecification>" + wrap);
                            content.append(space + space + "</businessRuleTask>" + wrap);
                        }
                    }
                }
            }
            content.append(wrap);
            content.append(space + space + "<!-- connections -->" + wrap);

            // 遍历连线
            List<RuleFlowItem> forkItemList = new ArrayList<RuleFlowItem>();
            //收集引用数据
            Map<String, RuleReferenceData> refMap = new HashMap();
            //冠军，挑战者信息
            Map<String, String> champion = new HashMap<>();
            String championInfoStr = "";
            if (alLine != null && alLine.size() > 0) {
                HashMap<String, List<RuleFlowCondition>> mapCondition = new HashMap<String, List<RuleFlowCondition>>();
                Map<String,ExtendNodeInfo> outCount = new HashMap<>();
                Map<String,ExtendNodeInfo> intCount = new HashMap<>();
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);
                    if(!outCount.containsKey(curLine.from)) {
                    	ExtendNodeInfo tmp = new ExtendNodeInfo();
                    	tmp.setCount(1);
                    	tmp.getRefLineList().add(curLine);
                    	tmp.setFrom(curLine.from);
                    	outCount.put(curLine.from, tmp);
                    }else {
                    	ExtendNodeInfo tmp = outCount.get(curLine.from);
                    	tmp.setCount(tmp.getCount()+1);
                    	tmp.getRefLineList().add(curLine);
                    	tmp.setFrom(curLine.from);
                    	outCount.put(curLine.from,tmp);
                    }
                    if(!intCount.containsKey(curLine.oriTo)) {
                    	ExtendNodeInfo tmp = new ExtendNodeInfo();
                    	tmp.setCount(1);
                    	tmp.getRefLineList().add(curLine);
                    	intCount.put(curLine.oriTo, tmp);
                    }else {
                    	ExtendNodeInfo tmp = intCount.get(curLine.oriTo);
                    	tmp.setCount(tmp.getCount()+1);
                    	tmp.getRefLineList().add(curLine);
                    	intCount.put(curLine.oriTo,tmp);
                    }
                }
                for(Entry<String,ExtendNodeInfo> entry:outCount.entrySet()) {
                	if(entry.getValue().getCount()>1) {
                		Node  chaNode=  isChampion(entry.getValue().getFrom(), alNode);
                		if (chaNode != null) {
	                		content.append(space + space + "<inclusiveGateway id=\"" + chaNode.id + "\" name=\"" + chaNode.id + "\" gatewayDirection=\"Diverging\"/>" + wrap);
                		}else {
	                		Node fork = new Node();
	                		fork.id="rect"+StringUtils.generateTenUuid();
	                		fork.type="fork";
	                		fork.x="10";
	                		fork.y="10";
	                		fork.width="10";
	                		fork.height="10";
	                		alNode.add(fork);
	                		Node forkTree = alNodeMap.get(entry.getValue().getFrom());
	                		String forkName = fork.id;
	                		if(forkTree!=null) {
	                			forkName = forkTree.name;
	                		}
	                		content.append(space + space + "<inclusiveGateway id=\"" + fork.id + "\" name=\"" + forkName + "\" gatewayDirection=\"Diverging\"/>" + wrap);
	                		entry.getValue().setNode(fork);
	                		Line newLine = new Line();
	                		newLine.from = entry.getKey();
	                		newLine.to = fork.id;
	                		newLine.oriTo = fork.id;
	                		alLine.add(newLine);
	                		List<RuleFlowCondition> conditionList = new ArrayList<>();
	                		for(Line item:entry.getValue().getRefLineList()) {
	                			item.from = fork.id;
	                			RuleFlowCondition citem = new RuleFlowCondition();
	                			citem.setFromTo(item.from+"-"+item.oriTo);
	                			citem.setItemStr(item.constaints);
	                			conditionList.add(citem);
	                		}
	                		fork.setConditionList(conditionList);
                		}	
                	}
                }
                for(Entry<String,ExtendNodeInfo> entry:intCount.entrySet()) {
                	if(entry.getValue().getCount()>1) {
                		Node join = new Node();
                		join.id="rect"+StringUtils.generateTenUuid();
                		join.type="join";
                		join.x="10";
                		join.y="10";
                		join.width="10";
                		join.height="10";
                		alNode.add(join);
                		content.append(space + space + "<exclusiveGateway id=\"" + join.id + "\" name=\"" + join.name + "\" gatewayDirection=\"Converging\"/>" + wrap);
                		entry.getValue().setNode(join);
                		Line newLine = new Line();
                		newLine.from = join.id;
                		newLine.to = entry.getKey();
                		newLine.oriTo = entry.getKey();
                		alLine.add(newLine);
                		for(Line item:entry.getValue().getRefLineList()) {
                			item.to = join.id;
                		}
                	}
                }
                
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);
                    String lineId = curLine.from + minus + curLine.oriTo;
                    String name = curLine.text;
                    Node cham = isChampion(curLine.from, alNode);
                    if (cham != null) {
                        RuleFlowCondition condition = null;
                        boolean championFlag = false;
						if (cham.constaints != null && cham.constaints.length() > 0){
							List<RuleFlowCondition> conditionList = null;
							if(mapCondition.containsKey(cham.id)){
								conditionList = mapCondition.get(cham.id);
							}else{
								String conditionStr = cham.constaints.replace("#", "\"");
								conditionList = JSON.parseArray(conditionStr, RuleFlowCondition.class);
								mapCondition.put(cham.id, conditionList);
							}
							for (int j = 0; j < conditionList.size(); j++) {
								RuleFlowCondition temp = conditionList.get(j);
								String isNull = String.valueOf(temp.getIsChampion());
								if(isNull.equals("null")) {
									break;
								}
								boolean flag = temp.getIsChampion();
								if(flag) {
									championFlag = true;
								}
								if(org.apache.commons.lang3.StringUtils.isEmpty(temp.getFromTo())){
									throw new Exception(cham.name+"信息异常，请重新保存分支!");
								}

								if(temp.getFromTo().equals(lineId)){
									condition = temp;
								}
							}
						}
						String seqName = StringUtils.generateTenUuid();
						if(championFlag) {
							boolean isChampion = condition.getIsChampion();
							if(isChampion){
								champion.put("champion", "true");
								champion.put("name", name);
								championInfoStr = " ruleHelper.getValue(dataMap,\"championInfo.champion\")==\"true\"";
								championInfo.add(champion);
							}else{
								Map<String, String> challenger = new HashMap<>();
								challenger.put("challenger", String.valueOf(i));
								challenger.put("name", name);
								championInfoStr = " ruleHelper.getValue(dataMap,\"championInfo.challenger\")==\""+i+"\"";
								championInfo.add(challenger);
							}
						}
						
                        content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\" name=\"" + seqName + "\" tns:priority=\"" + "0" + "\">" + wrap);
                        content.append(space + space + space + "<conditionExpression xsi:type=\"tFormalExpression\" >" +championInfoStr + "</conditionExpression>" + wrap);
                        content.append(space + space + "</sequenceFlow>" + wrap);
                    }else {
	                    // 当前线段的开始节点是否是分支节点
	                    Node fork = isFork(curLine, alNode);
	                    // 线的起始节点是分支节点
	                    if (fork != null) {
	                        // 分支节点条件
                                RuleFlowCondition condition = null;
	                            List<String>  clsList  = new  ArrayList<>();
	    						if (fork.getConditionList() != null && fork.getConditionList().size() > 0){
	    							List<RuleFlowCondition> conditionList = null;
	    							if(mapCondition.containsKey(fork.id)){
	    								conditionList = mapCondition.get(fork.id);
	    							}else{
	    								mapCondition.put(fork.id, fork.getConditionList());
	    								conditionList = fork.getConditionList();
	    							}
	    							for (int j = 0; j < conditionList.size(); j++) {
	    								RuleFlowCondition temp = conditionList.get(j);
	
	    								String tmpItemStr =temp.getItemStr().replace("@", "\"");
	    								if (!StringUtils.isEmpty(tmpItemStr)) {
		    								List<RuleFlowItem> itemList =JSON.parseArray(tmpItemStr, RuleFlowItem.class);
		    								if (itemList !=null  ) {
		    									for  (RuleFlowItem conFlowItem:itemList) {
			    								    String  conValue =	conFlowItem.getControlValue().replace("%", "\"");
			    								    conFlowItem.setControlValue(conValue);
			    								    if (conValue !=null && !conValue.equals("otherwise")) {
			    								    	clsList.add(conValue);
			    								    }
		    									}
		    								}
	    								}
	    								if(org.apache.commons.lang3.StringUtils.isEmpty(temp.getFromTo())){
	    									throw new Exception(fork.name+"信息异常，请重新保存分支!");
	    								}
	    								if(temp.getFromTo().equals(lineId)){
	    									condition = temp;
	    								}
	    							}
	    						}
	    						String mapStr = "";//默认条件都是可以走分支
	    						String seqName = StringUtils.generateTenUuid();

	                            if (condition!=null && !StringUtils.isEmpty(condition.getItemStr())) {
	                            	seqName = condition.getName();
	                                String forkItemStr = condition.getItemStr().replace("@", "\"");
	                                List<RuleFlowItem> conList = JSON.parseArray(forkItemStr, RuleFlowItem.class);
	                                forkItemList.addAll(conList);
	                                String  enmStr=null;
	   
	                                for (RuleFlowItem forkItem : conList) {
	                                    String dataType = forkItem.getDataType();
	                                    String domain = forkItem.getDomain();
	                                    String symbol = forkItem.getSymbol();
    								    String controlValue = forkItem.getControlValue().replace("%", "\"");
    								    forkItem.setControlValue(controlValue);
	                                    enmStr =null;
	                                    if (clsList.size()==0 && "otherwise".equals(controlValue)) {
	                                    	continue;
	                                    }else if (clsList.size()>0&& "otherwise".equals(controlValue) ) {
	                                    	String strList =StringUtils.join(clsList, ",");
	                                     	enmStr = "ruleHelper.isNotContains(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+strList+"\")";
	                                    }
	                                    if (dataType.toLowerCase().equals("string") || dataType.toLowerCase().equals("emun")) {
	                                        if (StringUtils.isNotEmpty(domain)) {
	                                            // 类型字符串、domain不为空、操作符为0:   not in
	                                        	controlValue = controlValue.substring(1, controlValue.length() - 1);
	                                        	if (controlValue != null) {
	                                        		controlValue=StringUtils.replace(controlValue, "\"", "");
	                              
	                                        	}
	                                            if (symbol.equals("0")) {
	                                            	enmStr = "ruleHelper.isNotContains(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+controlValue+"\")";
	                                            }
	                                            // 类型字符串、domain不为空、操作符为1:   in
	                                            else if (symbol.equals("1")) {
	                                            	enmStr = "ruleHelper.isExistsEnum(dataMap,\"" + forkItem.getClassName() + "." + forkItem.getNameEN() + "\""+",\""+controlValue+"\")";
	                                            }
	                                        } else {
	                                            if (symbol.equals("startsWith") || symbol.equals("endsWith")) {
	                                                symbol = "." + symbol;
	                                                controlValue = "(\"" + controlValue + "\")";
	                                            } else {
	                                                controlValue = "\"" + controlValue + "\"";
	                                            }
	                                        }
	                                    } else if (dataType.toLowerCase().equals("double") || dataType.toLowerCase().equals("long") || dataType.toLowerCase().equals("date")) {
	                                        // 操作符进行转译
	                                        if (symbol.equals(">")) {
	                                            symbol = "&gt;";
	                                        } else if (symbol.equals(">=")) {
	                                            symbol = "&gt;=";
	                                        } else if (symbol.equals("<")) {
	                                            symbol = "&lt;";
	                                        } else if (symbol.equals("<=")) {
	                                            symbol = "&lt;=";
	                                        }
	                                        symbol = " " + symbol + " ";
	                                        if (dataType.toLowerCase().equals("date")) {
	                                            controlValue = "\"" + controlValue + "\"";
	                                        }else {
	    							            //20171103 modify 
	    										if (controlValue.startsWith("{") && controlValue.endsWith("}")) {
	    											controlValue=StringUtils.replace(controlValue, "￥", "\"");
	    											Map<String, String> controlMap = (new ObjectMapper()).readValue(controlValue, Map.class);
	    											controlValue = genernalWhenStr(controlMap.get("className"),controlMap.get("nameEN"),"ruleflow"); 
	    											//controlValue = " ruleHelper.getValue(dataMap,\"" + controlMap.get("className") + "." + controlMap.get("nameEN") + "\")";
	    											String key = controlMap.get("className") + "|" + controlMap.get("nameEN") + "|in";
	    											ruleReferenceDataService.collectFromMap(controlMap, key, "in", ruleManage, refMap);
	    										}
	                                        }
	                                    } else if (dataType.toLowerCase().equals("boolean")) {
	                                        controlValue = "";
	                                        // 类型字符串、domain为空、操作符为0:   !=
	                                        if (symbol.equals("0")) {
	                                            controlValue = "false";
	                                        }
	                                        // 类型字符串、domain为空、操作符为1:   ==
	                                        else if (symbol.equals("1")) {
	                                            controlValue = "true";
	                                        }
	                                        symbol = " == ";
	                                    }
	                                    String leftOpt = forkItem.getLeftOpt();
	                                    if (!StringUtils.isEmpty(leftOpt)) {
	                                        leftOpt = leftOpt.toUpperCase();
	                                        leftOpt = leftOpt.replace("AND", "&amp;&amp;").replace("OR", "||");
	                                    }
	                                    String rightOpt = forkItem.getRightOpt();
	                                    if (!StringUtils.isEmpty(rightOpt)) {
	                                        rightOpt = rightOpt.toUpperCase();
	                                        rightOpt = rightOpt.replace("AND", "&amp;&amp;").replace("OR", "||");
	                                    }
	                                    leftOpt = leftOpt == null ? "" : leftOpt;
	                                    rightOpt = rightOpt == null ? "" : rightOpt;
	                                    if (enmStr != null) {
	                                    	mapStr +=leftOpt+enmStr +rightOpt;
	                                    }else {
	                                      String tmpStr = genernalWhenStr(forkItem.getClassName(),forkItem.getNameEN(),"ruleflow"); 
	                                      mapStr += leftOpt + tmpStr + symbol +" " + controlValue + rightOpt;
	                                    }
	                                }
	                            }
	                            if(StringUtils.isEmpty(mapStr)) {
	                            	mapStr = "ruleHelper.trueFlag==true";
	                            }
	                            String paraPriority = "0";
	                            content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\" name=\"" + seqName + "\" tns:priority=\"" + paraPriority + "\">" + wrap);
	                            content.append(space + space + space + "<conditionExpression xsi:type=\"tFormalExpression\" >" + mapStr+championInfoStr + "</conditionExpression>" + wrap);
	                            content.append(space + space + "</sequenceFlow>" + wrap);
	//                        } else {
	//                            content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\"/>" + wrap);
	//                        }
	                         
	                    } else {
	                        content.append(space + space + "<sequenceFlow id=\"" + lineId + "\" sourceRef=\"" + curLine.from + "\" targetRef=\"" + curLine.to + "\"/>" + wrap);
	                    }
                    } 
                }
            }
            content.append(space + "</process>" + wrap);
            content.append(wrap);
            content.append(space + "<bpmndi:BPMNDiagram>" + wrap);
            content.append(space + space + "<bpmndi:BPMNPlane bpmnElement=\"" + strFlag + "\">" + wrap);
            // 遍历节点
            if (alNode != null && alNode.size() > 0) {
                for (int i = 0; i < alNode.size(); i++) {
                    Node curNode = alNode.get(i);
                    if (curNode.type.equals("ruleFlow") || curNode.type.equals("dataInit") || curNode.type.equals("decisionTree") || curNode.type.equals("decisionTable") || curNode.type.equals("evaluationIndex") || curNode.type.equals("scoreModel") || curNode.type.equals("ruleGroup") || curNode.type.equals("policyRuleGroup")) {
                        curNode.width = "110";
                        curNode.height = "48";
                    }
                    content.append(space + space + space + "<bpmndi:BPMNShape bpmnElement=\"" + curNode.id + "\">" + wrap);
                    content.append(space + space + space + space + "<dc:Bounds x=\"" + curNode.x + "\" y=\"" + curNode.y + "\" width=\"" + curNode.width + "\" height=\"" + curNode.height + "\"/>" + wrap);
                    content.append(space + space + space + "</bpmndi:BPMNShape>" + wrap);
                }
            }
            content.append(wrap);
            // 遍历节点
            if (alLine != null && alLine.size() > 0) {
                for (int i = 0; i < alLine.size(); i++) {
                    Line curLine = alLine.get(i);

                    String lineId = curLine.from + minus + curLine.to;
                    content.append(space + space + space + "<bpmndi:BPMNEdge bpmnElement=\"" + lineId + "\">" + wrap);
                    Node nodeFrom = getNodeById(curLine.from, alNode);
                    String x = nodeFrom.x;
                    String y = nodeFrom.y;
                    String w = nodeFrom.width;
                    String h = nodeFrom.height;
                    x = calcValue(x, w);
                    y = calcValue(y, h);
                    content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);

                    //
                    String dots = curLine.dots;
                    if (dots != null && dots.trim().length() > 0) {
                        if (dots.indexOf(semicolon) >= 0) {
                            String[] arrDot = dots.split(semicolon);
                            for (int k = 0; k < arrDot.length; k++) {
                                String dot = arrDot[k];
                                String[] arr = dot.split(comma);
                                x = arr[0];
                                y = arr[1];

                                content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                            }
                        } else {
                            String[] arr = dots.split(comma);
                            x = arr[0];
                            y = arr[1];

                            content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                        }
                    }
                    Node nodeTo = getNodeById(curLine.to, alNode);
                    x = nodeTo.x;
                    y = nodeTo.y;
                    w = nodeTo.width;
                    h = nodeTo.height;

                    x = calcValue(x, w);
                    y = calcValue(y, h);

                    content.append(space + space + space + space + "<di:waypoint x=\"" + x + "\" y=\"" + y + "\"/>" + wrap);
                    content.append(space + space + space + "</bpmndi:BPMNEdge>" + wrap);
                }
            }
            content.append(space + space + "</bpmndi:BPMNPlane>" + wrap);
            content.append(space + "</bpmndi:BPMNDiagram>" + wrap);
            content.append("</definitions>" + wrap);
        }
        return content.toString();
    }

    public int countListFindName(RuleFlowModel ruleInfo){
        RuleManage ruleManage = new RuleManage();
        ruleManage.setId(ruleInfo.getManageId());
        ruleManage.setName(ruleInfo.getName());
        ruleManage.setRankRelationId(ruleInfo.getRankRelationId());
        return this.ruleManageService.countListFindName(ruleManage, RuleModelTypeFileEnum.RuleFlow.type);
    }
    
}